From a8f130244477596ee12ccc20baab8b00953215fe Mon Sep 17 00:00:00 2001 From: msyyc <70930885+msyyc@users.noreply.github.com> Date: Wed, 15 Jun 2022 10:18:07 +0800 Subject: [PATCH 1/4] remove lowlevel client test --- eng/pipelines/ci.yml | 29 ----------------------------- tasks.py | 2 +- 2 files changed, 1 insertion(+), 30 deletions(-) diff --git a/eng/pipelines/ci.yml b/eng/pipelines/ci.yml index 0c01e210a9b..6badc6d146b 100644 --- a/eng/pipelines/ci.yml +++ b/eng/pipelines/ci.yml @@ -110,18 +110,6 @@ jobs: testRunTitle: "$(OSName) Python $(PythonVersion) - legacy azure" searchFolder: "$(TestFolder)/azure/legacy" - - script: | - cd $(TestFolder)/azure/low-level - tox -e ci - displayName: 'Execute low-level "azure" Tests - Python $(PythonVersion)' - condition: succeededOrFailed() - - task: PublishTestResults@2 - condition: succeededOrFailed() - displayName: 'Publish low-level "azure" Test Results' - inputs: - testRunTitle: "$(OSName) Python $(PythonVersion) - low-level azure" - searchFolder: "$(TestFolder)/azure/low-level" - - script: | cd $(TestFolder)/azure/version-tolerant tox -e ci @@ -157,18 +145,6 @@ jobs: testRunTitle: "$(OSName) Python $(PythonVersion) - legacy vanilla" searchFolder: "$(TestFolder)/vanilla/legacy" - - script: | - cd $(TestFolder)/vanilla/low-level - tox -e ci - displayName: 'Execute low level "vanilla" Tests - Python $(PythonVersion)' - condition: succeededOrFailed() - - task: PublishTestResults@2 - displayName: 'Publish low level "vanilla" Test Results' - condition: succeededOrFailed() - inputs: - testRunTitle: "$(OSName) Python $(PythonVersion) - low level vanilla" - searchFolder: "$(TestFolder)/vanilla/low-level" - - script: | cd $(TestFolder)/vanilla/version-tolerant tox -e ci @@ -193,11 +169,6 @@ jobs: displayName: 'Mypy version-tolerant "vanilla" Tests - Python $(PythonVersion)' condition: and(succeededOrFailed(), eq(variables['PythonVersion'], '3.10')) - - script: | - cd $(TestFolder)/dpg/low-level - tox -e ci - displayName: 'Execute low level update "dpg" Tests - Python $(PythonVersion)' - condition: succeededOrFailed() - script: | cd $(TestFolder)/dpg/version-tolerant tox -e ci diff --git a/tasks.py b/tasks.py index ed40d31c4a2..3c3df7348eb 100644 --- a/tasks.py +++ b/tasks.py @@ -455,7 +455,7 @@ def regenerate( "low_level_client" if low_level_client else "", "legacy" if legacy else "", ] - generators = [g for g in generators if g] or ["legacy", "low_level_client", "version_tolerant"] + generators = [g for g in generators if g] or ["legacy", "version_tolerant"] folders = [ "vanilla" if vanilla else "", "azure" if azure else "", From eac172041b2dbe5cd09a840c8a778e776d3b80df Mon Sep 17 00:00:00 2001 From: msyyc <70930885+msyyc@users.noreply.github.com> Date: Wed, 15 Jun 2022 10:26:26 +0800 Subject: [PATCH 2/4] remove lowlevel from release pipeline --- eng/pipelines/publish-release.yml | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/eng/pipelines/publish-release.yml b/eng/pipelines/publish-release.yml index 44c5d38d520..740babcd97d 100644 --- a/eng/pipelines/publish-release.yml +++ b/eng/pipelines/publish-release.yml @@ -49,11 +49,6 @@ steps: tox -e ci displayName: 'Execute legacy "azure" Tests - Python $(PythonVersion)' - - script: | - cd $(TestFolder)/azure/low-level - tox -e ci - displayName: 'Execute low level "azure" Tests - Python $(PythonVersion)' - - script: | cd $(TestFolder)/azure/version-tolerant tox -e ci @@ -64,21 +59,11 @@ steps: tox -e ci displayName: 'Execute legacy "vanilla" Tests - Python $(PythonVersion)' - - script: | - cd $(TestFolder)/vanilla/low-level - tox -e ci - displayName: 'Execute low level "vanilla" Tests - Python $(PythonVersion)' - - script: | cd $(TestFolder)/vanilla/version-tolerant tox -e ci displayName: 'Execute version tolerant "vanilla" Tests - Python $(PythonVersion)' - - script: | - cd $(TestFolder)/dpg/low-level - tox -e ci - displayName: 'Execute low level "dpg" Tests - Python $(PythonVersion)' - - script: | cd $(TestFolder)/dpg/version-tolerant tox -e ci From 58a53126145a1d99b327ade86f50187c0679ad84 Mon Sep 17 00:00:00 2001 From: msyyc <70930885+msyyc@users.noreply.github.com> Date: Thu, 16 Jun 2022 11:23:09 +0800 Subject: [PATCH 3/4] remove test for llc --- eng/scripts/run_mypy.py | 4 +- eng/scripts/run_pylint.py | 2 +- tasks.py | 68 +- .../low-level/AcceptanceTests/__init__.py | 0 .../AcceptanceTests/asynctests/__init__.py | 25 - .../AcceptanceTests/asynctests/conftest.py | 42 - .../asynctests/test_azure_url.py | 45 - .../AcceptanceTests/asynctests/test_config.py | 56 - .../asynctests/test_duration.py | 71 - .../AcceptanceTests/asynctests/test_head.py | 65 - .../AcceptanceTests/asynctests/test_lro.py | 611 ---- .../AcceptanceTests/asynctests/test_paging.py | 348 -- .../asynctests/test_parameter.py | 237 -- .../AcceptanceTests/asynctests/test_xms.py | 99 - .../low-level/AcceptanceTests/conftest.py | 107 - .../AcceptanceTests/test_azure_url.py | 42 - .../low-level/AcceptanceTests/test_config.py | 56 - .../AcceptanceTests/test_duration.py | 66 - .../low-level/AcceptanceTests/test_head.py | 63 - .../low-level/AcceptanceTests/test_lro.py | 561 --- .../low-level/AcceptanceTests/test_paging.py | 299 -- .../AcceptanceTests/test_parameter.py | 216 -- .../low-level/AcceptanceTests/test_xms.py | 90 - .../low-level/AcceptanceTests/test_zzz.py | 92 - .../bodydurationlowlevel/__init__.py | 24 - .../bodydurationlowlevel/_client.py | 74 - .../bodydurationlowlevel/_configuration.py | 42 - .../bodydurationlowlevel/_patch.py | 20 - .../bodydurationlowlevel/_serialization.py | 1970 ----------- .../bodydurationlowlevel/_version.py | 9 - .../bodydurationlowlevel/aio/__init__.py | 21 - .../bodydurationlowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../bodydurationlowlevel/aio/_patch.py | 20 - .../bodydurationlowlevel/py.typed | 1 - .../bodydurationlowlevel/rest/__init__.py | 6 - .../rest/duration/__init__.py | 19 - .../rest/duration/_request_builders.py | 122 - .../AzureBodyDurationLowLevel/setup.py | 30 - .../__init__.py | 24 - .../azureparametergroupinglowlevel/_client.py | 74 - .../_configuration.py | 42 - .../azureparametergroupinglowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../azureparametergroupinglowlevel/_vendor.py | 17 - .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../aio/_patch.py | 20 - .../azureparametergroupinglowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/parameter_grouping/__init__.py | 23 - .../parameter_grouping/_request_builders.py | 264 -- .../AzureParameterGroupingLowLevel/setup.py | 30 - .../azurereportlowlevel/__init__.py | 24 - .../azurereportlowlevel/_client.py | 74 - .../azurereportlowlevel/_configuration.py | 42 - .../azurereportlowlevel/_patch.py | 20 - .../azurereportlowlevel/_serialization.py | 1970 ----------- .../azurereportlowlevel/_version.py | 9 - .../azurereportlowlevel/aio/__init__.py | 21 - .../azurereportlowlevel/aio/_client.py | 71 - .../azurereportlowlevel/aio/_configuration.py | 39 - .../azurereportlowlevel/aio/_patch.py | 20 - .../azurereportlowlevel/py.typed | 1 - .../azurereportlowlevel/rest/__init__.py | 13 - .../rest/_request_builders.py | 50 - .../AzureReportLowLevel/setup.py | 30 - .../__init__.py | 24 - .../azurespecialpropertieslowlevel/_client.py | 93 - .../_configuration.py | 72 - .../azurespecialpropertieslowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../azurespecialpropertieslowlevel/_vendor.py | 17 - .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 90 - .../aio/_configuration.py | 69 - .../aio/_patch.py | 20 - .../azurespecialpropertieslowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/api_version_default/__init__.py | 19 - .../api_version_default/_request_builders.py | 136 - .../rest/api_version_local/__init__.py | 19 - .../api_version_local/_request_builders.py | 149 - .../rest/header/__init__.py | 17 - .../rest/header/_request_builders.py | 101 - .../rest/odata/__init__.py | 13 - .../rest/odata/_request_builders.py | 59 - .../rest/skip_url_encoding/__init__.py | 25 - .../skip_url_encoding/_request_builders.py | 244 -- .../subscription_in_credentials/__init__.py | 21 - .../_request_builders.py | 194 - .../rest/subscription_in_method/__init__.py | 19 - .../_request_builders.py | 153 - .../rest/xms_client_request_id/__init__.py | 15 - .../_request_builders.py | 65 - .../AzureSpecialsLowLevel/setup.py | 30 - .../custombaseurllowlevel/__init__.py | 24 - .../custombaseurllowlevel/_client.py | 80 - .../custombaseurllowlevel/_configuration.py | 49 - .../custombaseurllowlevel/_patch.py | 20 - .../custombaseurllowlevel/_serialization.py | 1970 ----------- .../custombaseurllowlevel/_version.py | 9 - .../custombaseurllowlevel/aio/__init__.py | 21 - .../custombaseurllowlevel/aio/_client.py | 77 - .../aio/_configuration.py | 46 - .../custombaseurllowlevel/aio/_patch.py | 20 - .../custombaseurllowlevel/py.typed | 1 - .../custombaseurllowlevel/rest/__init__.py | 6 - .../rest/paths/__init__.py | 13 - .../rest/paths/_request_builders.py | 41 - .../CustomBaseUriLowLevel/setup.py | 30 - .../custombaseurlpaginglowlevel/__init__.py | 24 - .../custombaseurlpaginglowlevel/_client.py | 80 - .../_configuration.py | 51 - .../custombaseurlpaginglowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../custombaseurlpaginglowlevel/_vendor.py | 17 - .../custombaseurlpaginglowlevel/_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 77 - .../aio/_configuration.py | 48 - .../custombaseurlpaginglowlevel/aio/_patch.py | 20 - .../custombaseurlpaginglowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/paging/__init__.py | 17 - .../rest/paging/_request_builders.py | 100 - .../CustomUrlPagingLowLevel/setup.py | 30 - .../headexceptionslowlevel/__init__.py | 24 - .../headexceptionslowlevel/_client.py | 80 - .../headexceptionslowlevel/_configuration.py | 58 - .../headexceptionslowlevel/_patch.py | 20 - .../headexceptionslowlevel/_serialization.py | 1970 ----------- .../headexceptionslowlevel/_version.py | 9 - .../headexceptionslowlevel/aio/__init__.py | 21 - .../headexceptionslowlevel/aio/_client.py | 77 - .../aio/_configuration.py | 55 - .../headexceptionslowlevel/aio/_patch.py | 20 - .../headexceptionslowlevel/py.typed | 1 - .../headexceptionslowlevel/rest/__init__.py | 6 - .../rest/head_exception/__init__.py | 17 - .../rest/head_exception/_request_builders.py | 69 - .../HeadExceptionsLowLevel/setup.py | 30 - .../HeadLowLevel/headlowlevel/__init__.py | 24 - .../HeadLowLevel/headlowlevel/_client.py | 80 - .../headlowlevel/_configuration.py | 58 - .../HeadLowLevel/headlowlevel/_patch.py | 20 - .../headlowlevel/_serialization.py | 1970 ----------- .../HeadLowLevel/headlowlevel/_version.py | 9 - .../HeadLowLevel/headlowlevel/aio/__init__.py | 21 - .../HeadLowLevel/headlowlevel/aio/_client.py | 77 - .../headlowlevel/aio/_configuration.py | 55 - .../HeadLowLevel/headlowlevel/aio/_patch.py | 20 - .../HeadLowLevel/headlowlevel/py.typed | 1 - .../headlowlevel/rest/__init__.py | 6 - .../rest/http_success/__init__.py | 17 - .../rest/http_success/_request_builders.py | 69 - .../AcceptanceTests/HeadLowLevel/setup.py | 30 - .../LroLowLevel/lrolowlevel/__init__.py | 24 - .../LroLowLevel/lrolowlevel/_client.py | 80 - .../LroLowLevel/lrolowlevel/_configuration.py | 60 - .../LroLowLevel/lrolowlevel/_patch.py | 20 - .../LroLowLevel/lrolowlevel/_serialization.py | 1970 ----------- .../LroLowLevel/lrolowlevel/_version.py | 9 - .../LroLowLevel/lrolowlevel/aio/__init__.py | 21 - .../LroLowLevel/lrolowlevel/aio/_client.py | 77 - .../lrolowlevel/aio/_configuration.py | 57 - .../LroLowLevel/lrolowlevel/aio/_patch.py | 20 - .../LroLowLevel/lrolowlevel/py.typed | 1 - .../LroLowLevel/lrolowlevel/rest/__init__.py | 6 - .../rest/lr_os_custom_header/__init__.py | 19 - .../lr_os_custom_header/_request_builders.py | 436 --- .../lrolowlevel/rest/lro_retrys/__init__.py | 25 - .../rest/lro_retrys/_request_builders.py | 503 --- .../lrolowlevel/rest/lros/__init__.py | 99 - .../rest/lros/_request_builders.py | 3109 ----------------- .../lrolowlevel/rest/lrosads/__init__.py | 63 - .../rest/lrosads/_request_builders.py | 2001 ----------- .../AcceptanceTests/LroLowLevel/setup.py | 30 - .../__init__.py | 24 - .../_client.py | 80 - .../_configuration.py | 49 - .../_patch.py | 20 - .../_serialization.py | 1970 ----------- .../_vendor.py | 17 - .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 77 - .../aio/_configuration.py | 46 - .../aio/_patch.py | 20 - .../py.typed | 1 - .../rest/__init__.py | 15 - .../rest/_request_builders.py | 76 - .../setup.py | 30 - .../PagingLowLevel/paginglowlevel/__init__.py | 24 - .../PagingLowLevel/paginglowlevel/_client.py | 74 - .../paginglowlevel/_configuration.py | 42 - .../PagingLowLevel/paginglowlevel/_patch.py | 20 - .../paginglowlevel/_serialization.py | 1970 ----------- .../PagingLowLevel/paginglowlevel/_vendor.py | 17 - .../PagingLowLevel/paginglowlevel/_version.py | 9 - .../paginglowlevel/aio/__init__.py | 21 - .../paginglowlevel/aio/_client.py | 71 - .../paginglowlevel/aio/_configuration.py | 39 - .../paginglowlevel/aio/_patch.py | 20 - .../PagingLowLevel/paginglowlevel/py.typed | 1 - .../paginglowlevel/rest/__init__.py | 6 - .../paginglowlevel/rest/paging/__init__.py | 53 - .../rest/paging/_request_builders.py | 715 ---- .../AcceptanceTests/PagingLowLevel/setup.py | 30 - .../StorageManagementClientLowLevel/setup.py | 30 - .../storagelowlevel/__init__.py | 24 - .../storagelowlevel/_client.py | 93 - .../storagelowlevel/_configuration.py | 70 - .../storagelowlevel/_patch.py | 20 - .../storagelowlevel/_serialization.py | 1970 ----------- .../storagelowlevel/_vendor.py | 17 - .../storagelowlevel/_version.py | 9 - .../storagelowlevel/aio/__init__.py | 21 - .../storagelowlevel/aio/_client.py | 90 - .../storagelowlevel/aio/_configuration.py | 67 - .../storagelowlevel/aio/_patch.py | 20 - .../storagelowlevel/py.typed | 1 - .../storagelowlevel/rest/__init__.py | 6 - .../rest/storage_accounts/__init__.py | 29 - .../storage_accounts/_request_builders.py | 839 ----- .../storagelowlevel/rest/usage/__init__.py | 13 - .../rest/usage/_request_builders.py | 55 - .../SubscriptionIdApiVersionLowLevel/setup.py | 30 - .../__init__.py | 24 - .../_client.py | 92 - .../_configuration.py | 69 - .../_patch.py | 20 - .../_serialization.py | 1970 ----------- .../_vendor.py | 17 - .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 89 - .../aio/_configuration.py | 66 - .../aio/_patch.py | 20 - .../subscriptionidapiversionlowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/group/__init__.py | 13 - .../rest/group/_request_builders.py | 59 - .../low-level/coverage/report-azure.json | 143 - test/azure/low-level/coverage/report-dpg.json | 16 - .../low-level/coverage/report-optional.json | 50 - .../low-level/coverage/report-vanilla.json | 637 ---- test/azure/low-level/requirements.txt | 22 - test/azure/low-level/tox.ini | 16 - .../AcceptanceTests/asynctests/conftest.py | 62 - .../asynctests/test_service_driven_async.py | 123 - .../dpg/low-level/AcceptanceTests/conftest.py | 62 - .../AcceptanceTests/test_service_driven.py | 115 - .../dpg/low-level/AcceptanceTests/test_zzz.py | 74 - .../__init__.py | 24 - .../_client.py | 74 - .../_configuration.py | 42 - .../_dpg_client.py | 76 - .../_patch.py | 20 - .../_serialization.py | 1970 ----------- .../_vendor.py | 17 - .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../aio/_dpg_client.py | 72 - .../aio/_patch.py | 20 - .../py.typed | 1 - .../rest/__init__.py | 19 - .../rest/_request_builders.py | 232 -- .../setup.py | 30 - .../__init__.py | 24 - .../_client.py | 74 - .../_configuration.py | 42 - .../_dpg_client.py | 76 - .../dpgcustomizationinitiallowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../_vendor.py | 17 - .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../aio/_dpg_client.py | 72 - .../aio/_patch.py | 20 - .../dpgcustomizationinitiallowlevel/py.typed | 1 - .../rest/__init__.py | 19 - .../rest/_request_builders.py | 232 -- .../DPGCustomizationInitialLowLevel/setup.py | 30 - .../__init__.py | 24 - .../_client.py | 74 - .../_configuration.py | 42 - .../_dpg_client.py | 76 - .../dpgservicedriveninitiallowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../aio/_dpg_client.py | 72 - .../aio/_patch.py | 20 - .../dpgservicedriveninitiallowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/params/__init__.py | 21 - .../rest/params/_request_builders.py | 236 -- .../DPGServiceDrivenInitialLowLevel/setup.py | 30 - .../__init__.py | 24 - .../_client.py | 74 - .../_configuration.py | 42 - .../_dpg_client.py | 76 - .../_patch.py | 20 - .../_serialization.py | 1970 ----------- .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../aio/_dpg_client.py | 72 - .../aio/_patch.py | 20 - .../py.typed | 1 - .../rest/__init__.py | 6 - .../rest/params/__init__.py | 25 - .../rest/params/_request_builders.py | 304 -- .../setup.py | 30 - test/dpg/low-level/requirements.txt | 9 - test/dpg/low-level/tox.ini | 10 - .../low-level/AcceptanceTests/__init__.py | 0 .../AcceptanceTests/asynctests/__init__.py | 0 .../AcceptanceTests/asynctests/conftest.py | 50 - .../asynctests/test_additional_properties.py | 135 - .../asynctests/test_anything.py | 78 - .../AcceptanceTests/asynctests/test_array.py | 423 --- .../AcceptanceTests/asynctests/test_binary.py | 48 - .../AcceptanceTests/asynctests/test_bool.py | 79 - .../AcceptanceTests/asynctests/test_byte.py | 72 - .../asynctests/test_complex.py | 655 ---- .../AcceptanceTests/asynctests/test_config.py | 45 - .../asynctests/test_constants.py | 59 - .../asynctests/test_content_type.py | 49 - .../AcceptanceTests/asynctests/test_date.py | 94 - .../asynctests/test_datetime.py | 174 - .../asynctests/test_datetime_rfc.py | 99 - .../asynctests/test_dictionary.py | 427 --- .../asynctests/test_duration.py | 69 - .../asynctests/test_error_with_secrets.py | 59 - .../asynctests/test_extensible_enums.py | 77 - .../AcceptanceTests/asynctests/test_file.py | 99 - .../asynctests/test_form_data.py | 159 - .../AcceptanceTests/asynctests/test_header.py | 247 -- .../AcceptanceTests/asynctests/test_hooks.py | 56 - .../AcceptanceTests/asynctests/test_http.py | 540 --- .../asynctests/test_integer.py | 127 - .../asynctests/test_media_types.py | 111 - .../asynctests/test_merge_patch_json.py | 46 - .../asynctests/test_model_flattening.py | 300 -- .../asynctests/test_multiple_inheritance.py | 97 - .../asynctests/test_non_string_enums.py | 62 - .../AcceptanceTests/asynctests/test_number.py | 155 - .../asynctests/test_object_type.py | 60 - .../asynctests/test_parameterized_endpoint.py | 44 - .../asynctests/test_required_optional.py | 209 -- .../asynctests/test_reserved_words.py | 83 - .../asynctests/test_security.py | 53 - .../asynctests/test_send_request.py | 173 - .../asynctests/test_string_tests.py | 183 - .../AcceptanceTests/asynctests/test_time.py | 54 - .../AcceptanceTests/asynctests/test_url.py | 393 --- .../asynctests/test_urlencoded.py | 66 - .../asynctests/test_validation.py | 94 - .../AcceptanceTests/asynctests/test_xml.py | 262 -- .../low-level/AcceptanceTests/conftest.py | 123 - .../test_additional_properties.py | 127 - .../AcceptanceTests/test_anything.py | 68 - .../low-level/AcceptanceTests/test_array.py | 370 -- .../low-level/AcceptanceTests/test_binary.py | 48 - .../low-level/AcceptanceTests/test_bool.py | 71 - .../low-level/AcceptanceTests/test_byte.py | 65 - .../low-level/AcceptanceTests/test_complex.py | 619 ---- .../low-level/AcceptanceTests/test_config.py | 42 - .../AcceptanceTests/test_constants.py | 57 - .../AcceptanceTests/test_content_type.py | 106 - .../low-level/AcceptanceTests/test_date.py | 86 - .../AcceptanceTests/test_datetime.py | 160 - .../AcceptanceTests/test_datetime_rfc.py | 91 - .../AcceptanceTests/test_dictionary.py | 391 --- .../AcceptanceTests/test_duration.py | 66 - .../test_error_with_secrets.py | 56 - .../AcceptanceTests/test_extensible_enums.py | 73 - .../low-level/AcceptanceTests/test_file.py | 91 - .../AcceptanceTests/test_form_data.py | 153 - .../low-level/AcceptanceTests/test_header.py | 230 -- .../low-level/AcceptanceTests/test_hooks.py | 54 - .../low-level/AcceptanceTests/test_http.py | 496 --- .../low-level/AcceptanceTests/test_inputs.py | 79 - .../low-level/AcceptanceTests/test_integer.py | 119 - .../AcceptanceTests/test_media_types.py | 100 - .../AcceptanceTests/test_merge_patch_json.py | 44 - .../AcceptanceTests/test_model_flattening.py | 293 -- .../test_multiple_inheritance.py | 84 - .../AcceptanceTests/test_non_string_enums.py | 57 - .../low-level/AcceptanceTests/test_number.py | 139 - .../AcceptanceTests/test_object_type.py | 56 - .../test_parameterized_endpoint.py | 42 - .../AcceptanceTests/test_required_optional.py | 193 - .../AcceptanceTests/test_reserved_words.py | 75 - .../AcceptanceTests/test_security.py | 50 - .../AcceptanceTests/test_send_request.py | 171 - .../AcceptanceTests/test_string_tests.py | 171 - .../low-level/AcceptanceTests/test_time.py | 50 - .../low-level/AcceptanceTests/test_url.py | 347 -- .../AcceptanceTests/test_urlencoded.py | 64 - .../AcceptanceTests/test_validation.py | 85 - .../low-level/AcceptanceTests/test_xml.py | 240 -- .../low-level/AcceptanceTests/test_zzz.py | 120 - .../low-level/AcceptanceTests/utils.py | 38 - .../additionalpropertieslowlevel/__init__.py | 24 - .../additionalpropertieslowlevel/_client.py | 74 - .../_configuration.py | 42 - .../additionalpropertieslowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../additionalpropertieslowlevel/_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../aio/_patch.py | 20 - .../additionalpropertieslowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/pets/__init__.py | 23 - .../rest/pets/_request_builders.py | 522 --- .../AdditionalPropertiesLowLevel/setup.py | 30 - .../anythinglowlevel/__init__.py | 24 - .../anythinglowlevel/_client.py | 75 - .../anythinglowlevel/_configuration.py | 42 - .../anythinglowlevel/_patch.py | 20 - .../anythinglowlevel/_serialization.py | 1970 ----------- .../anythinglowlevel/_version.py | 9 - .../anythinglowlevel/aio/__init__.py | 21 - .../anythinglowlevel/aio/_client.py | 72 - .../anythinglowlevel/aio/_configuration.py | 39 - .../anythinglowlevel/aio/_patch.py | 20 - .../anythinglowlevel/py.typed | 1 - .../anythinglowlevel/rest/__init__.py | 23 - .../rest/_request_builders.py | 176 - .../AcceptanceTests/AnythingLowLevel/setup.py | 30 - .../bodyarraylowlevel/__init__.py | 24 - .../bodyarraylowlevel/_client.py | 74 - .../bodyarraylowlevel/_configuration.py | 42 - .../bodyarraylowlevel/_patch.py | 20 - .../bodyarraylowlevel/_serialization.py | 1970 ----------- .../bodyarraylowlevel/_version.py | 9 - .../bodyarraylowlevel/aio/__init__.py | 21 - .../bodyarraylowlevel/aio/_client.py | 71 - .../bodyarraylowlevel/aio/_configuration.py | 39 - .../bodyarraylowlevel/aio/_patch.py | 20 - .../bodyarraylowlevel/py.typed | 1 - .../bodyarraylowlevel/rest/__init__.py | 6 - .../bodyarraylowlevel/rest/array/__init__.py | 149 - .../rest/array/_request_builders.py | 2791 --------------- .../BodyArrayLowLevel/setup.py | 30 - .../bodybinarylowlevel/__init__.py | 24 - .../bodybinarylowlevel/_client.py | 74 - .../bodybinarylowlevel/_configuration.py | 42 - .../bodybinarylowlevel/_patch.py | 20 - .../bodybinarylowlevel/_serialization.py | 1970 ----------- .../bodybinarylowlevel/_version.py | 9 - .../bodybinarylowlevel/aio/__init__.py | 21 - .../bodybinarylowlevel/aio/_client.py | 71 - .../bodybinarylowlevel/aio/_configuration.py | 39 - .../bodybinarylowlevel/aio/_patch.py | 20 - .../bodybinarylowlevel/py.typed | 1 - .../bodybinarylowlevel/rest/__init__.py | 6 - .../rest/upload/__init__.py | 15 - .../rest/upload/_request_builders.py | 70 - .../BodyBinaryLowLevel/setup.py | 30 - .../bodybooleanlowlevel/__init__.py | 24 - .../bodybooleanlowlevel/_client.py | 74 - .../bodybooleanlowlevel/_configuration.py | 42 - .../bodybooleanlowlevel/_patch.py | 20 - .../bodybooleanlowlevel/_serialization.py | 1970 ----------- .../bodybooleanlowlevel/_version.py | 9 - .../bodybooleanlowlevel/aio/__init__.py | 21 - .../bodybooleanlowlevel/aio/_client.py | 71 - .../bodybooleanlowlevel/aio/_configuration.py | 39 - .../bodybooleanlowlevel/aio/_patch.py | 20 - .../bodybooleanlowlevel/py.typed | 1 - .../bodybooleanlowlevel/rest/__init__.py | 6 - .../bodybooleanlowlevel/rest/bool/__init__.py | 23 - .../rest/bool/_request_builders.py | 180 - .../BodyBooleanLowLevel/setup.py | 30 - .../bodybytelowlevel/__init__.py | 24 - .../bodybytelowlevel/_client.py | 74 - .../bodybytelowlevel/_configuration.py | 42 - .../bodybytelowlevel/_patch.py | 20 - .../bodybytelowlevel/_serialization.py | 1970 ----------- .../bodybytelowlevel/_version.py | 9 - .../bodybytelowlevel/aio/__init__.py | 21 - .../bodybytelowlevel/aio/_client.py | 71 - .../bodybytelowlevel/aio/_configuration.py | 39 - .../bodybytelowlevel/aio/_patch.py | 20 - .../bodybytelowlevel/py.typed | 1 - .../bodybytelowlevel/rest/__init__.py | 6 - .../bodybytelowlevel/rest/byte/__init__.py | 21 - .../rest/byte/_request_builders.py | 147 - .../AcceptanceTests/BodyByteLowLevel/setup.py | 30 - .../bodycomplexlowlevel/__init__.py | 24 - .../bodycomplexlowlevel/_client.py | 77 - .../bodycomplexlowlevel/_configuration.py | 48 - .../bodycomplexlowlevel/_patch.py | 20 - .../bodycomplexlowlevel/_serialization.py | 1970 ----------- .../bodycomplexlowlevel/_version.py | 9 - .../bodycomplexlowlevel/aio/__init__.py | 21 - .../bodycomplexlowlevel/aio/_client.py | 74 - .../bodycomplexlowlevel/aio/_configuration.py | 45 - .../bodycomplexlowlevel/aio/_patch.py | 20 - .../bodycomplexlowlevel/py.typed | 1 - .../bodycomplexlowlevel/rest/__init__.py | 6 - .../rest/array/__init__.py | 21 - .../rest/array/_request_builders.py | 263 -- .../rest/basic/__init__.py | 23 - .../rest/basic/_request_builders.py | 237 -- .../rest/dictionary/__init__.py | 23 - .../rest/dictionary/_request_builders.py | 289 -- .../rest/flattencomplex/__init__.py | 13 - .../rest/flattencomplex/_request_builders.py | 41 - .../rest/inheritance/__init__.py | 15 - .../rest/inheritance/_request_builders.py | 144 - .../rest/polymorphicrecursive/__init__.py | 15 - .../polymorphicrecursive/_request_builders.py | 337 -- .../rest/polymorphism/__init__.py | 29 - .../rest/polymorphism/_request_builders.py | 793 ----- .../rest/primitive/__init__.py | 55 - .../rest/primitive/_request_builders.py | 1197 ------- .../rest/readonlyproperty/__init__.py | 15 - .../readonlyproperty/_request_builders.py | 128 - .../BodyComplexLowLevel/setup.py | 30 - .../bodydatelowlevel/__init__.py | 24 - .../bodydatelowlevel/_client.py | 74 - .../bodydatelowlevel/_configuration.py | 42 - .../bodydatelowlevel/_patch.py | 20 - .../bodydatelowlevel/_serialization.py | 1970 ----------- .../bodydatelowlevel/_version.py | 9 - .../bodydatelowlevel/aio/__init__.py | 21 - .../bodydatelowlevel/aio/_client.py | 71 - .../bodydatelowlevel/aio/_configuration.py | 39 - .../bodydatelowlevel/aio/_patch.py | 20 - .../bodydatelowlevel/py.typed | 1 - .../bodydatelowlevel/rest/__init__.py | 6 - .../bodydatelowlevel/rest/date/__init__.py | 27 - .../rest/date/_request_builders.py | 227 -- .../AcceptanceTests/BodyDateLowLevel/setup.py | 30 - .../bodydatetimelowlevel/__init__.py | 24 - .../bodydatetimelowlevel/_client.py | 74 - .../bodydatetimelowlevel/_configuration.py | 42 - .../bodydatetimelowlevel/_patch.py | 20 - .../bodydatetimelowlevel/_serialization.py | 1970 ----------- .../bodydatetimelowlevel/_version.py | 9 - .../bodydatetimelowlevel/aio/__init__.py | 21 - .../bodydatetimelowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../bodydatetimelowlevel/aio/_patch.py | 20 - .../bodydatetimelowlevel/py.typed | 1 - .../bodydatetimelowlevel/rest/__init__.py | 6 - .../rest/datetime/__init__.py | 55 - .../rest/datetime/_request_builders.py | 608 ---- .../BodyDateTimeLowLevel/setup.py | 30 - .../bodydatetimerfc1123lowlevel/__init__.py | 24 - .../bodydatetimerfc1123lowlevel/_client.py | 74 - .../_configuration.py | 42 - .../bodydatetimerfc1123lowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../bodydatetimerfc1123lowlevel/_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../bodydatetimerfc1123lowlevel/aio/_patch.py | 20 - .../bodydatetimerfc1123lowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/datetimerfc1123/__init__.py | 29 - .../rest/datetimerfc1123/_request_builders.py | 252 -- .../BodyDateTimeRfc1123LowLevel/setup.py | 30 - .../bodydictionarylowlevel/__init__.py | 24 - .../bodydictionarylowlevel/_client.py | 74 - .../bodydictionarylowlevel/_configuration.py | 42 - .../bodydictionarylowlevel/_patch.py | 20 - .../bodydictionarylowlevel/_serialization.py | 1970 ----------- .../bodydictionarylowlevel/_version.py | 9 - .../bodydictionarylowlevel/aio/__init__.py | 21 - .../bodydictionarylowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../bodydictionarylowlevel/aio/_patch.py | 20 - .../bodydictionarylowlevel/py.typed | 1 - .../bodydictionarylowlevel/rest/__init__.py | 6 - .../rest/dictionary/__init__.py | 141 - .../rest/dictionary/_request_builders.py | 2532 -------------- .../BodyDictionaryLowLevel/setup.py | 30 - .../bodydurationlowlevel/__init__.py | 24 - .../bodydurationlowlevel/_client.py | 74 - .../bodydurationlowlevel/_configuration.py | 42 - .../bodydurationlowlevel/_patch.py | 20 - .../bodydurationlowlevel/_serialization.py | 1970 ----------- .../bodydurationlowlevel/_version.py | 9 - .../bodydurationlowlevel/aio/__init__.py | 21 - .../bodydurationlowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../bodydurationlowlevel/aio/_patch.py | 20 - .../bodydurationlowlevel/py.typed | 1 - .../bodydurationlowlevel/rest/__init__.py | 6 - .../rest/duration/__init__.py | 19 - .../rest/duration/_request_builders.py | 122 - .../BodyDurationLowLevel/setup.py | 30 - .../bodyfilelowlevel/__init__.py | 24 - .../bodyfilelowlevel/_client.py | 74 - .../bodyfilelowlevel/_configuration.py | 42 - .../bodyfilelowlevel/_patch.py | 20 - .../bodyfilelowlevel/_serialization.py | 1970 ----------- .../bodyfilelowlevel/_version.py | 9 - .../bodyfilelowlevel/aio/__init__.py | 21 - .../bodyfilelowlevel/aio/_client.py | 71 - .../bodyfilelowlevel/aio/_configuration.py | 39 - .../bodyfilelowlevel/aio/_patch.py | 20 - .../bodyfilelowlevel/py.typed | 1 - .../bodyfilelowlevel/rest/__init__.py | 6 - .../bodyfilelowlevel/rest/files/__init__.py | 17 - .../rest/files/_request_builders.py | 91 - .../AcceptanceTests/BodyFileLowLevel/setup.py | 30 - .../bodyformdatalowlevel/__init__.py | 24 - .../bodyformdatalowlevel/_client.py | 74 - .../bodyformdatalowlevel/_configuration.py | 42 - .../bodyformdatalowlevel/_patch.py | 20 - .../bodyformdatalowlevel/_serialization.py | 1970 ----------- .../bodyformdatalowlevel/_version.py | 9 - .../bodyformdatalowlevel/aio/__init__.py | 21 - .../bodyformdatalowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../bodyformdatalowlevel/aio/_patch.py | 20 - .../bodyformdatalowlevel/py.typed | 1 - .../bodyformdatalowlevel/rest/__init__.py | 6 - .../rest/formdata/__init__.py | 17 - .../rest/formdata/_request_builders.py | 118 - .../BodyFormDataLowLevel/setup.py | 30 - .../__init__.py | 24 - .../bodyformurlencodeddatalowlevel/_client.py | 74 - .../_configuration.py | 42 - .../bodyformurlencodeddatalowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../bodyformurlencodeddatalowlevel/_vendor.py | 17 - .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../aio/_patch.py | 20 - .../bodyformurlencodeddatalowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/formdataurlencoded/__init__.py | 15 - .../formdataurlencoded/_request_builders.py | 93 - .../BodyFormUrlEncodedDataLowLevel/setup.py | 30 - .../bodyintegerlowlevel/__init__.py | 24 - .../bodyintegerlowlevel/_client.py | 74 - .../bodyintegerlowlevel/_configuration.py | 42 - .../bodyintegerlowlevel/_patch.py | 20 - .../bodyintegerlowlevel/_serialization.py | 1970 ----------- .../bodyintegerlowlevel/_version.py | 9 - .../bodyintegerlowlevel/aio/__init__.py | 21 - .../bodyintegerlowlevel/aio/_client.py | 71 - .../bodyintegerlowlevel/aio/_configuration.py | 39 - .../bodyintegerlowlevel/aio/_patch.py | 20 - .../bodyintegerlowlevel/py.typed | 1 - .../bodyintegerlowlevel/rest/__init__.py | 6 - .../bodyintegerlowlevel/rest/int/__init__.py | 39 - .../rest/int/_request_builders.py | 392 --- .../BodyIntegerLowLevel/setup.py | 30 - .../bodynumberlowlevel/__init__.py | 24 - .../bodynumberlowlevel/_client.py | 74 - .../bodynumberlowlevel/_configuration.py | 42 - .../bodynumberlowlevel/_patch.py | 20 - .../bodynumberlowlevel/_serialization.py | 1970 ----------- .../bodynumberlowlevel/_version.py | 9 - .../bodynumberlowlevel/aio/__init__.py | 21 - .../bodynumberlowlevel/aio/_client.py | 71 - .../bodynumberlowlevel/aio/_configuration.py | 39 - .../bodynumberlowlevel/aio/_patch.py | 20 - .../bodynumberlowlevel/py.typed | 1 - .../bodynumberlowlevel/rest/__init__.py | 6 - .../rest/number/__init__.py | 59 - .../rest/number/_request_builders.py | 674 ---- .../BodyNumberLowLevel/setup.py | 30 - .../bodystringlowlevel/__init__.py | 24 - .../bodystringlowlevel/_client.py | 74 - .../bodystringlowlevel/_configuration.py | 42 - .../bodystringlowlevel/_patch.py | 20 - .../bodystringlowlevel/_serialization.py | 1970 ----------- .../bodystringlowlevel/_version.py | 9 - .../bodystringlowlevel/aio/__init__.py | 21 - .../bodystringlowlevel/aio/_client.py | 71 - .../bodystringlowlevel/aio/_configuration.py | 39 - .../bodystringlowlevel/aio/_patch.py | 20 - .../bodystringlowlevel/py.typed | 1 - .../bodystringlowlevel/rest/__init__.py | 6 - .../bodystringlowlevel/rest/enum/__init__.py | 23 - .../rest/enum/_request_builders.py | 245 -- .../rest/string/__init__.py | 37 - .../rest/string/_request_builders.py | 380 -- .../BodyStringLowLevel/setup.py | 30 - .../bodytimelowlevel/__init__.py | 24 - .../bodytimelowlevel/_client.py | 74 - .../bodytimelowlevel/_configuration.py | 42 - .../bodytimelowlevel/_patch.py | 20 - .../bodytimelowlevel/_serialization.py | 1970 ----------- .../bodytimelowlevel/_version.py | 9 - .../bodytimelowlevel/aio/__init__.py | 21 - .../bodytimelowlevel/aio/_client.py | 71 - .../bodytimelowlevel/aio/_configuration.py | 39 - .../bodytimelowlevel/aio/_patch.py | 20 - .../bodytimelowlevel/py.typed | 1 - .../bodytimelowlevel/rest/__init__.py | 6 - .../bodytimelowlevel/rest/time/__init__.py | 15 - .../rest/time/_request_builders.py | 72 - .../AcceptanceTests/BodyTimeLowLevel/setup.py | 30 - .../constantslowlevel/__init__.py | 24 - .../constantslowlevel/_client.py | 86 - .../constantslowlevel/_configuration.py | 61 - .../constantslowlevel/_patch.py | 20 - .../constantslowlevel/_serialization.py | 1970 ----------- .../constantslowlevel/_vendor.py | 17 - .../constantslowlevel/_version.py | 9 - .../constantslowlevel/aio/__init__.py | 21 - .../constantslowlevel/aio/_client.py | 83 - .../constantslowlevel/aio/_configuration.py | 58 - .../constantslowlevel/aio/_patch.py | 20 - .../constantslowlevel/py.typed | 1 - .../constantslowlevel/rest/__init__.py | 6 - .../rest/contants/__init__.py | 45 - .../rest/contants/_request_builders.py | 531 --- .../ConstantsLowLevel/setup.py | 30 - .../custombaseurllowlevel/__init__.py | 24 - .../custombaseurllowlevel/_client.py | 80 - .../custombaseurllowlevel/_configuration.py | 49 - .../custombaseurllowlevel/_patch.py | 20 - .../custombaseurllowlevel/_serialization.py | 1970 ----------- .../custombaseurllowlevel/_version.py | 9 - .../custombaseurllowlevel/aio/__init__.py | 21 - .../custombaseurllowlevel/aio/_client.py | 77 - .../aio/_configuration.py | 46 - .../custombaseurllowlevel/aio/_patch.py | 20 - .../custombaseurllowlevel/py.typed | 1 - .../custombaseurllowlevel/rest/__init__.py | 6 - .../rest/paths/__init__.py | 13 - .../rest/paths/_request_builders.py | 41 - .../CustomBaseUriLowLevel/setup.py | 30 - .../__init__.py | 24 - .../_client.py | 86 - .../_configuration.py | 56 - .../_patch.py | 20 - .../_serialization.py | 1970 ----------- .../_vendor.py | 17 - .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 83 - .../aio/_configuration.py | 53 - .../aio/_patch.py | 20 - .../custombaseurlmoreoptionslowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/paths/__init__.py | 13 - .../rest/paths/_request_builders.py | 61 - .../CustomBaseUriMoreOptionsLowLevel/setup.py | 30 - .../errorwithsecretslowlevel/__init__.py | 24 - .../errorwithsecretslowlevel/_client.py | 74 - .../_configuration.py | 42 - .../errorwithsecretslowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../errorwithsecretslowlevel/_version.py | 9 - .../errorwithsecretslowlevel/aio/__init__.py | 21 - .../errorwithsecretslowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../errorwithsecretslowlevel/aio/_patch.py | 20 - .../errorwithsecretslowlevel/py.typed | 1 - .../errorwithsecretslowlevel/rest/__init__.py | 15 - .../rest/_request_builders.py | 66 - .../ErrorWithSecretsLowLevel/setup.py | 30 - .../__init__.py | 24 - .../extensibleenumsswaggerlowlevel/_client.py | 74 - .../_configuration.py | 42 - .../extensibleenumsswaggerlowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../extensibleenumsswaggerlowlevel/_vendor.py | 17 - .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../aio/_patch.py | 20 - .../extensibleenumsswaggerlowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/pet/__init__.py | 15 - .../rest/pet/_request_builders.py | 143 - .../ExtensibleEnumsLowLevel/setup.py | 30 - .../HeaderLowLevel/headerlowlevel/__init__.py | 24 - .../HeaderLowLevel/headerlowlevel/_client.py | 74 - .../headerlowlevel/_configuration.py | 42 - .../HeaderLowLevel/headerlowlevel/_patch.py | 20 - .../headerlowlevel/_serialization.py | 1970 ----------- .../HeaderLowLevel/headerlowlevel/_version.py | 9 - .../headerlowlevel/aio/__init__.py | 21 - .../headerlowlevel/aio/_client.py | 71 - .../headerlowlevel/aio/_configuration.py | 39 - .../headerlowlevel/aio/_patch.py | 20 - .../HeaderLowLevel/headerlowlevel/py.typed | 1 - .../headerlowlevel/rest/__init__.py | 6 - .../headerlowlevel/rest/header/__init__.py | 69 - .../rest/header/_request_builders.py | 900 ----- .../AcceptanceTests/HeaderLowLevel/setup.py | 30 - .../httpinfrastructurelowlevel/__init__.py | 24 - .../httpinfrastructurelowlevel/_client.py | 74 - .../_configuration.py | 42 - .../httpinfrastructurelowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../httpinfrastructurelowlevel/_version.py | 9 - .../aio/__init__.py | 21 - .../httpinfrastructurelowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../httpinfrastructurelowlevel/aio/_patch.py | 20 - .../httpinfrastructurelowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/http_client_failure/__init__.py | 63 - .../http_client_failure/_request_builders.py | 744 ---- .../rest/http_failure/__init__.py | 17 - .../rest/http_failure/_request_builders.py | 91 - .../rest/http_redirects/__init__.py | 43 - .../rest/http_redirects/_request_builders.py | 461 --- .../rest/http_retry/__init__.py | 29 - .../rest/http_retry/_request_builders.py | 277 -- .../rest/http_server_failure/__init__.py | 19 - .../http_server_failure/_request_builders.py | 128 - .../rest/http_success/__init__.py | 49 - .../rest/http_success/_request_builders.py | 575 --- .../rest/multiple_responses/__init__.py | 79 - .../multiple_responses/_request_builders.py | 811 ----- .../AcceptanceTests/HttpLowLevel/setup.py | 30 - .../__init__.py | 24 - .../incorrecterrorresponselowlevel/_client.py | 75 - .../_configuration.py | 42 - .../incorrecterrorresponselowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 72 - .../aio/_configuration.py | 39 - .../aio/_patch.py | 20 - .../incorrecterrorresponselowlevel/py.typed | 1 - .../rest/__init__.py | 13 - .../rest/_request_builders.py | 34 - .../IncorrectErrorResponseLowLevel/setup.py | 30 - .../mediatypeslowlevel/__init__.py | 24 - .../mediatypeslowlevel/_client.py | 74 - .../mediatypeslowlevel/_configuration.py | 42 - .../mediatypeslowlevel/_patch.py | 20 - .../mediatypeslowlevel/_serialization.py | 1970 ----------- .../mediatypeslowlevel/_version.py | 9 - .../mediatypeslowlevel/aio/__init__.py | 21 - .../mediatypeslowlevel/aio/_client.py | 71 - .../mediatypeslowlevel/aio/_configuration.py | 39 - .../mediatypeslowlevel/aio/_patch.py | 20 - .../mediatypeslowlevel/py.typed | 1 - .../mediatypeslowlevel/rest/__init__.py | 25 - .../rest/_request_builders.py | 411 --- .../MediaTypesLowLevel/setup.py | 30 - .../mergepatchjsonlowlevel/__init__.py | 24 - .../mergepatchjsonlowlevel/_client.py | 74 - .../mergepatchjsonlowlevel/_configuration.py | 42 - .../mergepatchjsonlowlevel/_patch.py | 20 - .../mergepatchjsonlowlevel/_serialization.py | 1970 ----------- .../mergepatchjsonlowlevel/_version.py | 9 - .../mergepatchjsonlowlevel/aio/__init__.py | 21 - .../mergepatchjsonlowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../mergepatchjsonlowlevel/aio/_patch.py | 20 - .../mergepatchjsonlowlevel/py.typed | 1 - .../mergepatchjsonlowlevel/rest/__init__.py | 13 - .../rest/_request_builders.py | 53 - .../MergePatchJsonLowLevel/setup.py | 30 - .../modelflatteninglowlevel/__init__.py | 24 - .../modelflatteninglowlevel/_client.py | 74 - .../modelflatteninglowlevel/_configuration.py | 42 - .../modelflatteninglowlevel/_patch.py | 20 - .../modelflatteninglowlevel/_serialization.py | 1970 ----------- .../modelflatteninglowlevel/_vendor.py | 17 - .../modelflatteninglowlevel/_version.py | 9 - .../modelflatteninglowlevel/aio/__init__.py | 21 - .../modelflatteninglowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../modelflatteninglowlevel/aio/_patch.py | 20 - .../modelflatteninglowlevel/py.typed | 1 - .../modelflatteninglowlevel/rest/__init__.py | 33 - .../rest/_request_builders.py | 853 ----- .../ModelFlatteningLowLevel/setup.py | 30 - .../multipleinheritancelowlevel/__init__.py | 24 - .../multipleinheritancelowlevel/_client.py | 74 - .../_configuration.py | 42 - .../multipleinheritancelowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../multipleinheritancelowlevel/_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../multipleinheritancelowlevel/aio/_patch.py | 20 - .../multipleinheritancelowlevel/py.typed | 1 - .../rest/__init__.py | 31 - .../rest/_request_builders.py | 564 --- .../MultipleInheritanceLowLevel/setup.py | 30 - .../nooperationslowlevel/__init__.py | 23 - .../nooperationslowlevel/_patch.py | 20 - .../nooperationslowlevel/_serialization.py | 1970 ----------- .../nooperationslowlevel/_version.py | 9 - .../nooperationslowlevel/py.typed | 1 - .../NoOperationsLowLevel/setup.py | 30 - .../nonstringenumslowlevel/__init__.py | 24 - .../nonstringenumslowlevel/_client.py | 74 - .../nonstringenumslowlevel/_configuration.py | 42 - .../nonstringenumslowlevel/_patch.py | 20 - .../nonstringenumslowlevel/_serialization.py | 1970 ----------- .../nonstringenumslowlevel/_version.py | 9 - .../nonstringenumslowlevel/aio/__init__.py | 21 - .../nonstringenumslowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../nonstringenumslowlevel/aio/_patch.py | 20 - .../nonstringenumslowlevel/py.typed | 1 - .../nonstringenumslowlevel/rest/__init__.py | 6 - .../rest/float/__init__.py | 15 - .../rest/float/_request_builders.py | 72 - .../rest/int/__init__.py | 15 - .../rest/int/_request_builders.py | 72 - .../NonStringEnumsLowLevel/setup.py | 30 - .../objecttypelowlevel/__init__.py | 24 - .../objecttypelowlevel/_client.py | 74 - .../objecttypelowlevel/_configuration.py | 42 - .../objecttypelowlevel/_patch.py | 20 - .../objecttypelowlevel/_serialization.py | 1970 ----------- .../objecttypelowlevel/_version.py | 9 - .../objecttypelowlevel/aio/__init__.py | 21 - .../objecttypelowlevel/aio/_client.py | 71 - .../objecttypelowlevel/aio/_configuration.py | 39 - .../objecttypelowlevel/aio/_patch.py | 20 - .../objecttypelowlevel/py.typed | 1 - .../objecttypelowlevel/rest/__init__.py | 15 - .../rest/_request_builders.py | 80 - .../ObjectTypeLowLevel/setup.py | 30 - .../parameterflatteninglowlevel/__init__.py | 24 - .../parameterflatteninglowlevel/_client.py | 74 - .../_configuration.py | 42 - .../parameterflatteninglowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../parameterflatteninglowlevel/_vendor.py | 17 - .../parameterflatteninglowlevel/_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../parameterflatteninglowlevel/aio/_patch.py | 20 - .../parameterflatteninglowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/availability_sets/__init__.py | 13 - .../availability_sets/_request_builders.py | 124 - .../ParameterFlatteningLowLevel/setup.py | 30 - .../parameterizedendpointlowlevel/__init__.py | 24 - .../parameterizedendpointlowlevel/_client.py | 79 - .../_configuration.py | 48 - .../parameterizedendpointlowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../parameterizedendpointlowlevel/_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 76 - .../aio/_configuration.py | 45 - .../aio/_patch.py | 20 - .../parameterizedendpointlowlevel/py.typed | 1 - .../rest/__init__.py | 13 - .../rest/_request_builders.py | 33 - .../ParameterizedEndpointLowLevel/setup.py | 30 - .../ReportLowLevel/reportlowlevel/__init__.py | 24 - .../ReportLowLevel/reportlowlevel/_client.py | 74 - .../reportlowlevel/_configuration.py | 42 - .../ReportLowLevel/reportlowlevel/_patch.py | 20 - .../reportlowlevel/_serialization.py | 1970 ----------- .../ReportLowLevel/reportlowlevel/_version.py | 9 - .../reportlowlevel/aio/__init__.py | 21 - .../reportlowlevel/aio/_client.py | 71 - .../reportlowlevel/aio/_configuration.py | 39 - .../reportlowlevel/aio/_patch.py | 20 - .../ReportLowLevel/reportlowlevel/py.typed | 1 - .../reportlowlevel/rest/__init__.py | 15 - .../reportlowlevel/rest/_request_builders.py | 84 - .../AcceptanceTests/ReportLowLevel/setup.py | 30 - .../requiredoptionallowlevel/__init__.py | 24 - .../requiredoptionallowlevel/_client.py | 93 - .../_configuration.py | 62 - .../requiredoptionallowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../requiredoptionallowlevel/_vendor.py | 17 - .../requiredoptionallowlevel/_version.py | 9 - .../requiredoptionallowlevel/aio/__init__.py | 21 - .../requiredoptionallowlevel/aio/_client.py | 90 - .../aio/_configuration.py | 59 - .../requiredoptionallowlevel/aio/_patch.py | 20 - .../requiredoptionallowlevel/py.typed | 1 - .../requiredoptionallowlevel/rest/__init__.py | 6 - .../rest/explicit/__init__.py | 59 - .../rest/explicit/_request_builders.py | 1407 -------- .../rest/implicit/__init__.py | 27 - .../rest/implicit/_request_builders.py | 267 -- .../RequiredOptionalLowLevel/setup.py | 30 - .../reservedwordslowlevel/__init__.py | 24 - .../reservedwordslowlevel/_client.py | 74 - .../reservedwordslowlevel/_configuration.py | 42 - .../reservedwordslowlevel/_patch.py | 20 - .../reservedwordslowlevel/_serialization.py | 1970 ----------- .../reservedwordslowlevel/_vendor.py | 17 - .../reservedwordslowlevel/_version.py | 9 - .../reservedwordslowlevel/aio/__init__.py | 21 - .../reservedwordslowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../reservedwordslowlevel/aio/_patch.py | 20 - .../reservedwordslowlevel/py.typed | 1 - .../reservedwordslowlevel/rest/__init__.py | 21 - .../rest/_request_builders.py | 198 -- .../rest/import_operations/__init__.py | 13 - .../import_operations/_request_builders.py | 47 - .../ReservedWordsLowLevel/setup.py | 30 - .../securityaadswaggerlowlevel/__init__.py | 24 - .../securityaadswaggerlowlevel/_client.py | 80 - .../_configuration.py | 57 - .../securityaadswaggerlowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../securityaadswaggerlowlevel/_version.py | 9 - .../aio/__init__.py | 21 - .../securityaadswaggerlowlevel/aio/_client.py | 77 - .../aio/_configuration.py | 54 - .../securityaadswaggerlowlevel/aio/_patch.py | 20 - .../securityaadswaggerlowlevel/py.typed | 1 - .../rest/__init__.py | 13 - .../rest/_request_builders.py | 33 - .../SecurityAadSwaggerLowLevel/setup.py | 30 - .../securitykeyswaggerlowlevel/__init__.py | 24 - .../securitykeyswaggerlowlevel/_client.py | 79 - .../_configuration.py | 51 - .../securitykeyswaggerlowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../securitykeyswaggerlowlevel/_version.py | 9 - .../aio/__init__.py | 21 - .../securitykeyswaggerlowlevel/aio/_client.py | 76 - .../aio/_configuration.py | 48 - .../securitykeyswaggerlowlevel/aio/_patch.py | 20 - .../securitykeyswaggerlowlevel/py.typed | 1 - .../rest/__init__.py | 13 - .../rest/_request_builders.py | 33 - .../SecurityKeySwaggerLowLevel/setup.py | 30 - .../AcceptanceTests/UrlLowLevel/setup.py | 30 - .../UrlLowLevel/urllowlevel/__init__.py | 24 - .../UrlLowLevel/urllowlevel/_client.py | 88 - .../UrlLowLevel/urllowlevel/_configuration.py | 52 - .../UrlLowLevel/urllowlevel/_patch.py | 20 - .../UrlLowLevel/urllowlevel/_serialization.py | 1970 ----------- .../UrlLowLevel/urllowlevel/_vendor.py | 17 - .../UrlLowLevel/urllowlevel/_version.py | 9 - .../UrlLowLevel/urllowlevel/aio/__init__.py | 21 - .../UrlLowLevel/urllowlevel/aio/_client.py | 85 - .../urllowlevel/aio/_configuration.py | 49 - .../UrlLowLevel/urllowlevel/aio/_patch.py | 20 - .../UrlLowLevel/urllowlevel/py.typed | 1 - .../UrlLowLevel/urllowlevel/rest/__init__.py | 6 - .../urllowlevel/rest/path_items/__init__.py | 19 - .../rest/path_items/_request_builders.py | 284 -- .../urllowlevel/rest/paths/__init__.py | 65 - .../rest/paths/_request_builders.py | 928 ----- .../urllowlevel/rest/queries/__init__.py | 81 - .../rest/queries/_request_builders.py | 1173 ------- .../UrlMultiCollectionFormatLowLevel/setup.py | 30 - .../__init__.py | 24 - .../_client.py | 74 - .../_configuration.py | 44 - .../_patch.py | 20 - .../_serialization.py | 1970 ----------- .../_version.py | 9 - .../aio/__init__.py | 21 - .../aio/_client.py | 71 - .../aio/_configuration.py | 41 - .../aio/_patch.py | 20 - .../urlmulticollectionformatlowlevel/py.typed | 1 - .../rest/__init__.py | 6 - .../rest/queries/__init__.py | 17 - .../rest/queries/_request_builders.py | 122 - .../ValidationLowLevel/setup.py | 30 - .../validationlowlevel/__init__.py | 24 - .../validationlowlevel/_client.py | 79 - .../validationlowlevel/_configuration.py | 54 - .../validationlowlevel/_patch.py | 20 - .../validationlowlevel/_serialization.py | 1970 ----------- .../validationlowlevel/_vendor.py | 17 - .../validationlowlevel/_version.py | 9 - .../validationlowlevel/aio/__init__.py | 21 - .../validationlowlevel/aio/_client.py | 76 - .../validationlowlevel/aio/_configuration.py | 51 - .../validationlowlevel/aio/_patch.py | 20 - .../validationlowlevel/py.typed | 1 - .../validationlowlevel/rest/__init__.py | 19 - .../rest/_request_builders.py | 371 -- .../AcceptanceTests/XmlLowLevel/setup.py | 30 - .../xmlservicelowlevel/__init__.py | 24 - .../XmlLowLevel/xmlservicelowlevel/_client.py | 74 - .../xmlservicelowlevel/_configuration.py | 42 - .../XmlLowLevel/xmlservicelowlevel/_patch.py | 20 - .../xmlservicelowlevel/_serialization.py | 1970 ----------- .../xmlservicelowlevel/_version.py | 9 - .../xmlservicelowlevel/aio/__init__.py | 21 - .../xmlservicelowlevel/aio/_client.py | 71 - .../xmlservicelowlevel/aio/_configuration.py | 39 - .../xmlservicelowlevel/aio/_patch.py | 20 - .../XmlLowLevel/xmlservicelowlevel/py.typed | 1 - .../xmlservicelowlevel/rest/__init__.py | 6 - .../xmlservicelowlevel/rest/xml/__init__.py | 79 - .../rest/xml/_request_builders.py | 1289 ------- .../XmsErrorResponseLowLevel/setup.py | 30 - .../xmserrorresponselowlevel/__init__.py | 24 - .../xmserrorresponselowlevel/_client.py | 74 - .../_configuration.py | 42 - .../xmserrorresponselowlevel/_patch.py | 20 - .../_serialization.py | 1970 ----------- .../xmserrorresponselowlevel/_vendor.py | 17 - .../xmserrorresponselowlevel/_version.py | 9 - .../xmserrorresponselowlevel/aio/__init__.py | 21 - .../xmserrorresponselowlevel/aio/_client.py | 71 - .../aio/_configuration.py | 39 - .../xmserrorresponselowlevel/aio/_patch.py | 20 - .../xmserrorresponselowlevel/py.typed | 1 - .../xmserrorresponselowlevel/rest/__init__.py | 6 - .../rest/pet/__init__.py | 17 - .../rest/pet/_request_builders.py | 115 - .../low-level/coverage/report-optional.json | 50 - .../low-level/coverage/report-vanilla.json | 627 ---- test/vanilla/low-level/requirements.txt | 53 - test/vanilla/low-level/tox.ini | 16 - 1138 files changed, 8 insertions(+), 205995 deletions(-) delete mode 100644 test/azure/low-level/AcceptanceTests/__init__.py delete mode 100644 test/azure/low-level/AcceptanceTests/asynctests/__init__.py delete mode 100644 test/azure/low-level/AcceptanceTests/asynctests/conftest.py delete mode 100644 test/azure/low-level/AcceptanceTests/asynctests/test_azure_url.py delete mode 100644 test/azure/low-level/AcceptanceTests/asynctests/test_config.py delete mode 100644 test/azure/low-level/AcceptanceTests/asynctests/test_duration.py delete mode 100644 test/azure/low-level/AcceptanceTests/asynctests/test_head.py delete mode 100644 test/azure/low-level/AcceptanceTests/asynctests/test_lro.py delete mode 100644 test/azure/low-level/AcceptanceTests/asynctests/test_paging.py delete mode 100644 test/azure/low-level/AcceptanceTests/asynctests/test_parameter.py delete mode 100644 test/azure/low-level/AcceptanceTests/asynctests/test_xms.py delete mode 100644 test/azure/low-level/AcceptanceTests/conftest.py delete mode 100644 test/azure/low-level/AcceptanceTests/test_azure_url.py delete mode 100644 test/azure/low-level/AcceptanceTests/test_config.py delete mode 100644 test/azure/low-level/AcceptanceTests/test_duration.py delete mode 100644 test/azure/low-level/AcceptanceTests/test_head.py delete mode 100644 test/azure/low-level/AcceptanceTests/test_lro.py delete mode 100644 test/azure/low-level/AcceptanceTests/test_paging.py delete mode 100644 test/azure/low-level/AcceptanceTests/test_parameter.py delete mode 100644 test/azure/low-level/AcceptanceTests/test_xms.py delete mode 100644 test/azure/low-level/AcceptanceTests/test_zzz.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/duration/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/duration/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_vendor.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/parameter_grouping/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/parameter_grouping/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/rest/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_vendor.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_default/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_default/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_local/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_local/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/header/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/header/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/odata/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/odata/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/skip_url_encoding/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/skip_url_encoding/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_credentials/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_credentials/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_method/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_method/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/xms_client_request_id/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/xms_client_request_id/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_vendor.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/paging/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/paging/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/head_exception/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/head_exception/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/http_success/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/http_success/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lr_os_custom_header/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lr_os_custom_header/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lro_retrys/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lro_retrys/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lros/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lros/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lrosads/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lrosads/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_vendor.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/rest/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_vendor.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/paging/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/paging/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_vendor.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/storage_accounts/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/storage_accounts/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/usage/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/usage/_request_builders.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/setup.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_serialization.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_vendor.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_version.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_client.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_configuration.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_patch.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/py.typed delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/group/__init__.py delete mode 100644 test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/group/_request_builders.py delete mode 100644 test/azure/low-level/coverage/report-azure.json delete mode 100644 test/azure/low-level/coverage/report-dpg.json delete mode 100644 test/azure/low-level/coverage/report-optional.json delete mode 100644 test/azure/low-level/coverage/report-vanilla.json delete mode 100644 test/azure/low-level/requirements.txt delete mode 100644 test/azure/low-level/tox.ini delete mode 100644 test/dpg/low-level/AcceptanceTests/asynctests/conftest.py delete mode 100644 test/dpg/low-level/AcceptanceTests/asynctests/test_service_driven_async.py delete mode 100644 test/dpg/low-level/AcceptanceTests/conftest.py delete mode 100644 test/dpg/low-level/AcceptanceTests/test_service_driven.py delete mode 100644 test/dpg/low-level/AcceptanceTests/test_zzz.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_configuration.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_dpg_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_patch.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_serialization.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_vendor.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_version.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_configuration.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_dpg_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_patch.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/py.typed delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/rest/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/rest/_request_builders.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/setup.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_configuration.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_dpg_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_patch.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_serialization.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_vendor.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_version.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_configuration.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_dpg_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_patch.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/py.typed delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/rest/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/rest/_request_builders.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/setup.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_configuration.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_dpg_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_patch.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_serialization.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_version.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_configuration.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_dpg_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_patch.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/py.typed delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/params/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/params/_request_builders.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/setup.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_configuration.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_dpg_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_patch.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_serialization.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_version.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_configuration.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_dpg_client.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_patch.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/py.typed delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/params/__init__.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/params/_request_builders.py delete mode 100644 test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/setup.py delete mode 100644 test/dpg/low-level/requirements.txt delete mode 100644 test/dpg/low-level/tox.ini delete mode 100644 test/vanilla/low-level/AcceptanceTests/__init__.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/__init__.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/conftest.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_additional_properties.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_anything.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_array.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_binary.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_bool.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_byte.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_complex.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_config.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_constants.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_content_type.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_date.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_datetime.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_datetime_rfc.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_dictionary.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_duration.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_error_with_secrets.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_extensible_enums.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_file.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_form_data.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_header.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_hooks.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_http.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_integer.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_media_types.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_merge_patch_json.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_model_flattening.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_multiple_inheritance.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_non_string_enums.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_number.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_object_type.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_parameterized_endpoint.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_required_optional.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_reserved_words.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_security.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_send_request.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_string_tests.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_time.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_url.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_urlencoded.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_validation.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/asynctests/test_xml.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/conftest.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_additional_properties.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_anything.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_array.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_binary.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_bool.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_byte.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_complex.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_config.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_constants.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_content_type.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_date.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_datetime.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_datetime_rfc.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_dictionary.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_duration.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_error_with_secrets.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_extensible_enums.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_file.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_form_data.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_header.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_hooks.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_http.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_inputs.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_integer.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_media_types.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_merge_patch_json.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_model_flattening.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_multiple_inheritance.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_non_string_enums.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_number.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_object_type.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_parameterized_endpoint.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_required_optional.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_reserved_words.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_security.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_send_request.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_string_tests.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_time.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_url.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_urlencoded.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_validation.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_xml.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/test_zzz.py delete mode 100644 test/vanilla/low-level/AcceptanceTests/utils.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/pets/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/pets/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/array/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/array/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/upload/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/upload/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/bool/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/bool/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/byte/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/byte/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/array/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/array/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/basic/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/basic/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/dictionary/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/dictionary/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/flattencomplex/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/flattencomplex/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/inheritance/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/inheritance/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphicrecursive/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphicrecursive/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphism/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphism/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/primitive/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/primitive/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/readonlyproperty/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/readonlyproperty/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/date/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/date/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/datetime/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/datetime/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/datetimerfc1123/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/datetimerfc1123/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/dictionary/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/dictionary/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/duration/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/duration/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/files/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/files/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/formdata/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/formdata/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_vendor.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/formdataurlencoded/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/formdataurlencoded/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/int/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/int/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/number/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/number/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/enum/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/enum/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/string/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/string/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/time/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/time/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_vendor.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/contants/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/contants/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_vendor.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/paths/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/paths/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_vendor.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/pet/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/pet/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/header/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/header/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_client_failure/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_client_failure/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_failure/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_failure/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_redirects/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_redirects/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_retry/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_retry/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_server_failure/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_server_failure/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_success/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_success/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/multiple_responses/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/multiple_responses/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_vendor.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/float/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/float/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/int/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/int/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_vendor.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/availability_sets/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/availability_sets/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_vendor.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/explicit/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/explicit/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/implicit/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/implicit/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_vendor.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/import_operations/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/import_operations/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_vendor.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/path_items/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/path_items/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/paths/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/paths/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/queries/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/queries/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/queries/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/queries/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_vendor.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/rest/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/xml/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/xml/_request_builders.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/setup.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_serialization.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_vendor.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_version.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_client.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_configuration.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_patch.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/py.typed delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/pet/__init__.py delete mode 100644 test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/pet/_request_builders.py delete mode 100644 test/vanilla/low-level/coverage/report-optional.json delete mode 100644 test/vanilla/low-level/coverage/report-vanilla.json delete mode 100644 test/vanilla/low-level/requirements.txt delete mode 100644 test/vanilla/low-level/tox.ini diff --git a/eng/scripts/run_mypy.py b/eng/scripts/run_mypy.py index c9ed2a22ccb..29114b18a44 100644 --- a/eng/scripts/run_mypy.py +++ b/eng/scripts/run_mypy.py @@ -46,14 +46,14 @@ def _single_dir_mypy(mod): "-t", "--test-folder", dest="test_folder", - help="The test folder we're in. Can be 'azure', 'llc', 'multiapi', or 'vanilla'", + help="The test folder we're in. Can be 'azure', 'multiapi', or 'vanilla'", required=True, ) parser.add_argument( "-g", "--generator", dest="generator", - help="The generator we're using. Can be 'legacy', 'version-tolerant', or 'low-level'.", + help="The generator we're using. Can be 'legacy', 'version-tolerant'.", required=True, ) parser.add_argument( diff --git a/eng/scripts/run_pylint.py b/eng/scripts/run_pylint.py index 002451950f1..fa1158f86d9 100644 --- a/eng/scripts/run_pylint.py +++ b/eng/scripts/run_pylint.py @@ -57,7 +57,7 @@ def _single_dir_pylint(mod): "-g", "--generator", dest="generator", - help="The generator we're using. Can be 'legacy', 'version-tolerant', or 'low-level'.", + help="The generator we're using. Can be 'legacy', 'version-tolerant'.", required=True, ) parser.add_argument( diff --git a/tasks.py b/tasks.py index 3c3df7348eb..72e75d499b5 100644 --- a/tasks.py +++ b/tasks.py @@ -24,7 +24,6 @@ class _SwaggerGroup(str, Enum): class _Generator(Enum): LEGACY = "legacy" VERSION_TOLERANT = "version_tolerant" - LOW_LEVEL_CLIENT = "low_level_client" class Config(NamedTuple): generator: _Generator @@ -196,14 +195,9 @@ def _get_config( else: generation_section = "azure" - low_level_client = kwargs.pop("low_level_client", False) version_tolerant = kwargs.pop("version_tolerant", False) - if low_level_client: - package_name += "LowLevel" - generation_section += "/low-level" - generator = _Generator.LOW_LEVEL_CLIENT - elif version_tolerant: + if version_tolerant: package_name += "VersionTolerant" generation_section += "/version-tolerant" generator = _Generator.VERSION_TOLERANT @@ -223,17 +217,13 @@ def _build_flags( 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, {})) - low_level_client = kwargs.get("low_level_client", False) version_tolerant = kwargs.get("version_tolerant", False) - client_side_validation = package_name in _PACKAGES_WITH_CLIENT_SIDE_VALIDATION and not (low_level_client or version_tolerant) + 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())) generator, output_folder = _get_config(swagger_group, package_name, **kwargs) - if generator == _Generator.LOW_LEVEL_CLIENT: - override_flags["low-level-client"] = True - namespace += "lowlevel" - elif generator == _Generator.VERSION_TOLERANT: + if generator == _Generator.VERSION_TOLERANT: override_flags["version-tolerant"] = True namespace += "versiontolerant" else: @@ -328,9 +318,7 @@ def _regenerate( _run_autorest(post_process_cmds, debug=debug) def _prepare_mapping_and_regenerate(c, mapping, swagger_group, swagger_name=None, debug=False, **kwargs): - if kwargs.get("low_level_client", False): - generator = _Generator.LOW_LEVEL_CLIENT - elif kwargs.get("version_tolerant", False): + if kwargs.get("version_tolerant", False): generator = _Generator.VERSION_TOLERANT else: generator = _Generator.LEGACY @@ -348,30 +336,6 @@ def regenerate_vanilla_legacy(c, swagger_name=None, debug=False, **kwargs): if not swagger_name: regenerate_package_mode(c, swagger_group=_SwaggerGroup.VANILLA) -@task -def regenerate_dpg_low_level_client(c, swagger_name=None, debug=False, **kwargs): - return _prepare_mapping_and_regenerate( - c, - _DPG_SWAGGER_MAPPINGS, - _SwaggerGroup.DPG, - swagger_name, - debug, - low_level_client=True, - **kwargs - ) - -@task -def regenerate_vanilla_low_level_client(c, swagger_name=None, debug=False, **kwargs): - return _prepare_mapping_and_regenerate( - c, - _VANILLA_SWAGGER_MAPPINGS, - _SwaggerGroup.VANILLA, - swagger_name, - debug, - low_level_client=True, - **kwargs - ) - @task def regenerate_dpg_version_tolerant(c, swagger_name=None, debug=False, **kwargs): _prepare_mapping_and_regenerate( @@ -403,10 +367,6 @@ def regenerate_azure_legacy(c, swagger_name=None, debug=False, **kwargs): regenerate_custom_poller_pager_legacy(c, debug) regenerate_package_mode(c, swagger_group=_SwaggerGroup.AZURE) -@task -def regenerate_azure_low_level_client(c, swagger_name=None, debug=False, **kwargs): - return _prepare_mapping_and_regenerate(c, _AZURE_SWAGGER_MAPPINGS, _SwaggerGroup.AZURE, swagger_name, debug, low_level_client=True, **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) @@ -417,10 +377,6 @@ def regenerate_azure_version_tolerant(c, swagger_name=None, debug=False, **kwarg 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) -@task -def regenerate_azure_arm_low_level_client(c, swagger_name=None, debug=False, **kwargs): - return _prepare_mapping_and_regenerate(c, _AZURE_ARM_SWAGGER_MAPPINGS, _SwaggerGroup.AZURE_ARM, swagger_name, debug, low_level_client=True, **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) @@ -441,7 +397,6 @@ def regenerate( swagger_name=None, debug=False, version_tolerant=False, - low_level_client=False, legacy=False, vanilla=False, azure=False, @@ -452,7 +407,6 @@ def regenerate( raise ValueError("Can not specify legacy flag and dpg flag at the same time.") generators = [ "version_tolerant" if version_tolerant else "", - "low_level_client" if low_level_client else "", "legacy" if legacy else "", ] generators = [g for g in generators if g] or ["legacy", "version_tolerant"] @@ -466,7 +420,6 @@ def regenerate( if not folder_flags: mapping = { "legacy": regenerate_legacy, - "low_level_client": regenerate_low_level_client, "version_tolerant": regenerate_version_tolerant, } funcs = [mapping[g] for g in generators if g in mapping.keys()] @@ -479,10 +432,6 @@ def regenerate( ("version_tolerant", "azure"): regenerate_azure_version_tolerant, ("version_tolerant", "azure_arm"): regenerate_azure_arm_version_tolerant, ("version_tolerant", "dpg"): regenerate_dpg_version_tolerant, - ("low_level_client", "vanilla"): regenerate_vanilla_low_level_client, - ("low_level_client", "azure"): regenerate_azure_low_level_client, - ("low_level_client", "azure_arm"): regenerate_azure_arm_low_level_client, - ("low_level_client", "dpg"): regenerate_dpg_low_level_client, } funcs = [ v for k, v in mapping.items() if k in itertools.product(generators, folder_flags) @@ -490,13 +439,6 @@ def regenerate( for func in funcs: func(c, swagger_name, debug) -@task -def regenerate_low_level_client(c, swagger_name=None, debug=False): - regenerate_dpg_low_level_client(c, swagger_name, debug) - regenerate_vanilla_low_level_client(c, swagger_name, debug) - regenerate_azure_low_level_client(c, swagger_name, debug) - regenerate_azure_arm_low_level_client(c, swagger_name, debug) - @task def regenerate_version_tolerant(c, swagger_name=None, debug=False): regenerate_dpg_version_tolerant(c, swagger_name, debug) @@ -511,7 +453,7 @@ def test(c): cmd = 'tox -e ci' autorest_types = ["azure", "vanilla"] - gen_types = ["legacy", "low-level", "version-tolerant"] + gen_types = ["legacy", "version-tolerant"] for autorest_type, gen_type in itertools.product(autorest_types, gen_types): os.chdir(f"{base_dir}/test/{autorest_type}/{gen_type}") c.run(cmd) diff --git a/test/azure/low-level/AcceptanceTests/__init__.py b/test/azure/low-level/AcceptanceTests/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/test/azure/low-level/AcceptanceTests/asynctests/__init__.py b/test/azure/low-level/AcceptanceTests/asynctests/__init__.py deleted file mode 100644 index 9ecdd4ff2c4..00000000000 --- a/test/azure/low-level/AcceptanceTests/asynctests/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# 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/test/azure/low-level/AcceptanceTests/asynctests/conftest.py b/test/azure/low-level/AcceptanceTests/asynctests/conftest.py deleted file mode 100644 index 2cca5243a79..00000000000 --- a/test/azure/low-level/AcceptanceTests/asynctests/conftest.py +++ /dev/null @@ -1,42 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest - -@pytest.fixture() -def base_send_request(): - async def send_request(client, request, **kwargs): - response = await client.send_request(request, **kwargs) - response.raise_for_status() - return response - return send_request - -@pytest.fixture() -def base_send_request_json_response(): - async def send_request_json_response(client, request): - response = await client.send_request(request) - response.raise_for_status() - return response.json() - return send_request_json_response \ No newline at end of file diff --git a/test/azure/low-level/AcceptanceTests/asynctests/test_azure_url.py b/test/azure/low-level/AcceptanceTests/asynctests/test_azure_url.py deleted file mode 100644 index 0f39d5a107a..00000000000 --- a/test/azure/low-level/AcceptanceTests/asynctests/test_azure_url.py +++ /dev/null @@ -1,45 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from uuid import uuid4 -import pytest - -from subscriptionidapiversionlowlevel.aio import MicrosoftAzureTestUrl -from subscriptionidapiversionlowlevel.rest import group - - -@pytest.mark.asyncio -async def test_azure_url(credential, authentication_policy): - - sub_id = str(uuid4()) - - async with MicrosoftAzureTestUrl(credential, sub_id, authentication_policy=authentication_policy) as client: - request = group.build_get_sample_resource_group_request(subscription_id=sub_id, resource_group_name="testgroup101") - response = await client.send_request(request) - response.raise_for_status() - response_json = response.json() - assert response_json['name'] == 'testgroup101' - assert response_json['location'] == "West US" diff --git a/test/azure/low-level/AcceptanceTests/asynctests/test_config.py b/test/azure/low-level/AcceptanceTests/asynctests/test_config.py deleted file mode 100644 index 675cd235e19..00000000000 --- a/test/azure/low-level/AcceptanceTests/asynctests/test_config.py +++ /dev/null @@ -1,56 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from azure.mgmt.core.policies import ARMHttpLoggingPolicy -# Head is azure-arm -from headlowlevel.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"} - ) - 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"}) - -@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'] - -@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: - assert client._config.credential_scopes == ["http://i-should-be-the-only-credential"] diff --git a/test/azure/low-level/AcceptanceTests/asynctests/test_duration.py b/test/azure/low-level/AcceptanceTests/asynctests/test_duration.py deleted file mode 100644 index 82b5fd3949e..00000000000 --- a/test/azure/low-level/AcceptanceTests/asynctests/test_duration.py +++ /dev/null @@ -1,71 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from async_generator import yield_, async_generator -from datetime import timedelta -import pytest - -import isodate -from bodydurationlowlevel.aio import AutoRestDurationTestService -from bodydurationlowlevel.rest import duration - - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestDurationTestService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_get_null_and_invalid(send_request, send_request_json_response): - request = duration.build_get_null_request() - assert (await send_request(request)).text() == '' - - # in llc, we don't raise deserialization error - request = duration.build_get_invalid_request() - with pytest.raises(isodate.ISO8601Error): - isodate.parse_duration(await send_request_json_response(request)) - -@pytest.mark.asyncio -async def test_positive_duration(send_request, send_request_json_response): - request = duration.build_get_positive_duration_request() - response = isodate.parse_duration(await send_request_json_response(request)) - assert response == isodate.Duration(4, 45005, 0, years=3, months=6) - delta = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) - request = duration.build_put_positive_duration_request(json=isodate.duration_isoformat(delta)) - await send_request(request) diff --git a/test/azure/low-level/AcceptanceTests/asynctests/test_head.py b/test/azure/low-level/AcceptanceTests/asynctests/test_head.py deleted file mode 100644 index 792ce783c2f..00000000000 --- a/test/azure/low-level/AcceptanceTests/asynctests/test_head.py +++ /dev/null @@ -1,65 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from headlowlevel.aio import AutoRestHeadTestService -from headlowlevel.rest import http_success -from headexceptionslowlevel.aio import AutoRestHeadExceptionTestService -from headexceptionslowlevel.rest import head_exception -from azure.core.exceptions import HttpResponseError - -import pytest - -@pytest.mark.asyncio -async def test_head(credential, authentication_policy): - async with AutoRestHeadTestService(credential, authentication_policy=authentication_policy) as client: - request = http_success.build_head200_request() - response = await client.send_request(request) - response.raise_for_status() - - request = http_success.build_head204_request() - response = await client.send_request(request) - response.raise_for_status() - - request = http_success.build_head404_request() - response = await client.send_request(request) - with pytest.raises(HttpResponseError): - response.raise_for_status() - -@pytest.mark.asyncio -async def test_head_exception(credential, authentication_policy): - async with AutoRestHeadExceptionTestService(credential, authentication_policy=authentication_policy) as client: - request = head_exception.build_head200_request() - response = await client.send_request(request) - response.raise_for_status() - - request = head_exception.build_head204_request() - response = await client.send_request(request) - response.raise_for_status() - - request = head_exception.build_head404_request() - response = await client.send_request(request) - with pytest.raises(HttpResponseError): - response.raise_for_status() diff --git a/test/azure/low-level/AcceptanceTests/asynctests/test_lro.py b/test/azure/low-level/AcceptanceTests/asynctests/test_lro.py deleted file mode 100644 index 82f6ebc15db..00000000000 --- a/test/azure/low-level/AcceptanceTests/asynctests/test_lro.py +++ /dev/null @@ -1,611 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import time -from async_generator import yield_, async_generator -from azure.core.pipeline.transport import HttpRequest - -from azure.core.exceptions import DecodeError, HttpResponseError -from azure.core.pipeline.policies import ContentDecodePolicy, AsyncRetryPolicy, HeadersPolicy, RequestIdPolicy -from azure.core.polling import AsyncLROPoller, AsyncNoPolling - -from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling - -from lrolowlevel.aio import AutoRestLongRunningOperationTestService -from lrolowlevel.rest import lr_os_custom_header, lro_retrys, lros, lrosads -from lrolowlevel._serialization import Serializer, Deserializer - -try: - from urlparse import urlparse -except ImportError: - from urllib.parse import urlparse - -import pytest - -POLLING_INTERVAL = 0 - -class AutorestTestARMPolling(AsyncARMPolling): - - def _polling_cookie(self, response): - """Collect retry cookie - we only want to do this for the test server - at this point, unless we implement a proper cookie policy. - - :returns: Dictionary containing a cookie header if required, - 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', '')} - 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)) - -@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: - await 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'} - -@pytest.fixture -def get_long_running_output(deserializer): - # this is the default deserializer, just returns deserialized object - def _callback(pipeline_response): - return deserializer("object", pipeline_response.http_response) - return _callback - -@pytest.fixture -def get_long_running_output_return_none(): - # for use if the swagger has no defined return object, so we - # follow the convenience layer, and just return none - def _callback(pipeline_response): - return None - return _callback - -@pytest.fixture -def get_poller(get_long_running_output, client): - - async def _callback(request, **kwargs): - request.url = client._client.format_url(request.url) - pipeline_response = await client._client._pipeline.run(request) - pipeline_response.http_response.raise_for_status() - polling = kwargs.pop("polling", True) - deserializer = kwargs.pop("get_long_running_output", get_long_running_output) - polling_method = kwargs.pop("polling_method", None) - if not polling_method: - polling_method = AutorestTestARMPolling(kwargs.pop("polling_interval", 0)) if polling else AsyncNoPolling() - return AsyncLROPoller(client._client, pipeline_response, deserializer, polling_method) - return _callback - -def _check_message_in_error(ex, message): - try: - assert ex.value.message.lower() == message.lower() - except AssertionError: - assert message.lower() in ex.value.message.lower() - -@pytest.fixture -def assert_polling_raises_with_message(get_poller): - async def _callback(request, message, **kwargs): - poller = await get_poller(request, **kwargs) - with pytest.raises(HttpResponseError) as ex: - await poller.wait() - _check_message_in_error(ex, message) - return _callback - -@pytest.fixture -def assert_initial_call_raises_with_message(get_poller): - async def _callback(request, message, **kwargs): - with pytest.raises(HttpResponseError) as ex: - await get_poller(request, **kwargs) # this makes the initial call - _check_message_in_error(ex, message) - return _callback - -@pytest.fixture() -def serializer(): - return Serializer() - -@pytest.fixture() -def deserializer(): - return Deserializer() - - -@pytest.mark.asyncio -async def test_post_double_headers_final_continuation_token(client, get_poller, get_long_running_output): - request = lros.build_post_double_headers_final_location_get_request() - - poller = await get_poller(request) - continuation_token = poller.continuation_token() - - poller = AsyncLROPoller.from_continuation_token( - polling_method=AsyncARMPolling(0), - continuation_token=continuation_token, - client=client._client, - deserialization_callback=get_long_running_output, - ) - product = await poller.result() - assert product['id'] == "100" - -@pytest.mark.asyncio -async def test_post_double_headers_final(get_poller): - request = lros.build_post_double_headers_final_location_get_request() - poller = await get_poller(request) - product = await poller.result() - assert product['id'] == "100" - - polling_method = AutorestTestARMPolling(0, lro_options={"final-state-via": "azure-async-operation"}) - request = lros.build_post_double_headers_final_azure_header_get_request() - product = await (await get_poller(request, polling_method=polling_method)).result() - assert product['id'] == "100" - -@pytest.mark.asyncio -async def test_post_double_headers_default(get_poller): - # This test will work as long as the default is Location - request = lros.build_post_double_headers_final_azure_header_get_default_request() - product = await (await get_poller(request)).result() - assert product['id'] == "100" - -@pytest.mark.asyncio -async def test_happy_put201_creating_succeeded200(get_poller): - request = lros.build_put201_creating_succeeded200_request() - process = await (await get_poller(request)).result() - assert "Succeeded" == process['properties']['provisioningState'] - - # Testing AsyncNoPolling - request = lros.build_put201_creating_succeeded200_request() - process = await (await get_poller(request, polling=False)).result() - assert "Creating" == process['properties']['provisioningState'] - -@pytest.mark.asyncio -async def test_happy_put201_creating_failed200(assert_polling_raises_with_message, get_poller): - request = lros.build_put201_creating_failed200_request() - await assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - - request = lros.build_put201_creating_failed200_request() - process = await (await get_poller(request, polling=False)).result() - assert "Created" == process['properties']['provisioningState'] - -@pytest.mark.asyncio -async def test_happy_put200_updating_succeeded204(get_poller): - request = lros.build_put200_updating_succeeded204_request() - process = await (await get_poller(request)).result() - assert "Succeeded" == process['properties']['provisioningState'] - - process = await (await get_poller(request, polling=False)).result() - assert "Updating" == process['properties']['provisioningState'] - -@pytest.mark.asyncio -async def test_happy_put200_acceptedcanceled200(get_poller, assert_polling_raises_with_message): - request = lros.build_put200_acceptedcanceled200_request() - await assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - - request = lros.build_put200_acceptedcanceled200_request() - process = await (await get_poller(request, polling=False)).result() - assert "Accepted" == process['properties']['provisioningState'] - -@pytest.mark.asyncio -async def test_happy_put_no_header_in_retry(get_poller): - request = lros.build_put_no_header_in_retry_request() - process = await (await get_poller(request)).result() - assert "Succeeded" == process['properties']['provisioningState'] - - request = lros.build_put_async_no_header_in_retry_request() - process = await (await get_poller(request)).result() - assert "Succeeded" == process['properties']['provisioningState'] - -@pytest.mark.asyncio -async def test_happy_put_sub_resource(get_poller): - request = lros.build_put_sub_resource_request() - process = await (await get_poller(request)).result() - assert "Succeeded" == process['properties']['provisioningState'] - - request = lros.build_put_async_sub_resource_request() - process = await (await get_poller(request)).result() - assert "Succeeded" == process['properties']['provisioningState'] - -@pytest.mark.asyncio -async def test_happy_put_non_resource(get_poller): - request = lros.build_put_non_resource_request() - process = await (await get_poller(request)).result() - assert "100" == process['id'] - - request = lros.build_put_async_non_resource_request() - process = await (await get_poller(request)).result() - assert "100" == process['id'] - -@pytest.mark.asyncio -async def test_happy_put200_succeeded(get_poller): - request = lros.build_put200_succeeded_request() - process = await (await get_poller(request)).result() - assert "Succeeded" == process['properties']['provisioningState'] - - request = lros.build_put200_succeeded_no_state_request() - process = await (await get_poller(request)).result() - assert "100" == process['id'] - -@pytest.mark.asyncio -async def test_put201_succeeded(get_poller): - request = lros.build_put201_succeeded_request() - process = await (await get_poller(request)).result() - - assert "Succeeded" == process['properties']['provisioningState'] - assert "100" == process['id'] - assert "foo" == process['name'] - -@pytest.mark.asyncio -async def test_happy_put202_retry200(get_poller): - request = lros.build_put202_retry200_request() - process = await (await get_poller(request)).result() - assert "100" == process['id'] - -@pytest.mark.asyncio -async def test_happy_put_retry_succeeded(get_poller): - request = lros.build_put_async_retry_succeeded_request() - process = await (await get_poller(request)).result() - assert "Succeeded" == process['properties']['provisioningState'] - - request = lros.build_put_async_no_retry_succeeded_request() - process = await (await get_poller(request)).result() - assert "Succeeded" == process['properties']['provisioningState'] - -@pytest.mark.asyncio -async def test_happy_put_retry_failed_canceled(get_poller, assert_polling_raises_with_message): - request = lros.build_put_async_retry_failed_request() - await assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - - request = lros.build_put_async_no_retrycanceled_request() - await assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - -@pytest.mark.asyncio -async def test_post202_retry200(get_poller, get_long_running_output_return_none): - request = lros.build_post202_retry200_request() - process = await (await get_poller(request, get_long_running_output=get_long_running_output_return_none)).result() - assert process is None - -@pytest.mark.asyncio -async def test_happy_delete(get_poller): - request = lros.build_delete204_succeeded_request() - assert await (await get_poller(request)).result() is None - - request = lros.build_delete202_retry200_request() - assert await (await get_poller(request)).result() is None - - request = lros.build_delete202_no_retry204_request() - assert await (await get_poller(request)).result() is None - -@pytest.mark.asyncio -async def test_happy_delete_no_header_in_retry(get_poller, get_long_running_output_return_none): - request = lros.build_delete_no_header_in_retry_request() - assert await (await get_poller(request)).result() is None - - request = lros.build_delete_async_no_header_in_retry_request() - assert await (await get_poller(request, get_long_running_output=get_long_running_output_return_none)).result() is None - -@pytest.mark.asyncio -async def test_happy_delete_async_retry_failed_canceled(assert_polling_raises_with_message): - request = lros.build_delete_async_retrycanceled_request() - await assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - - request = lros.build_delete_async_retry_failed_request() - await assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - -@pytest.mark.asyncio -async def test_happy_delete_async_succeeded(get_poller, get_long_running_output_return_none): - request = lros.build_delete_async_no_retry_succeeded_request() - assert await (await get_poller(request, get_long_running_output=get_long_running_output_return_none)).result() is None - - request = lros.build_delete_async_retry_succeeded_request() - assert await (await get_poller(request, get_long_running_output=get_long_running_output_return_none)).result() is None - -@pytest.mark.asyncio -async def test_happy_delete_provisioning(get_poller): - request = lros.build_delete_provisioning202_accepted200_succeeded_request() - process = await (await get_poller(request)).result() - assert "Succeeded" == process['properties']['provisioningState'] - - request = lros.build_delete_provisioning202_deletingcanceled200_request() - result = await (await get_poller(request)).result() - assert result['properties']['provisioningState'] == 'Canceled' - - request = lros.build_delete_provisioning202_deleting_failed200_request() - result = await (await get_poller(request)).result() - assert result['properties']['provisioningState'] == 'Failed' - -@pytest.mark.asyncio -async def test_happy_post(get_poller): - request = lros.build_post202_no_retry204_request() - assert await (await get_poller(request)).result() is None - - request = lros.build_post200_with_payload_request() - - sku = await (await get_poller(request)).result() - assert sku['id'] == '1' - -@pytest.mark.asyncio -async def test_happy_post_async_retry_failed_canceled(assert_polling_raises_with_message): - request = lros.build_post_async_retry_failed_request() - await assert_polling_raises_with_message(request, "Internal Server Error") - - request = lros.build_post_async_retrycanceled_request() - await assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - -@pytest.mark.asyncio -async def test_happy_post_async_succeeded(get_poller): - request = lros.build_post_async_retry_succeeded_request() - prod = await (await get_poller(request)).result() - assert prod['id'] == "100" - - request = lros.build_post_async_no_retry_succeeded_request() - prod = await (await get_poller(request)).result() - assert prod['id'] == "100" - -@pytest.mark.asyncio -async def test_retrys_put(get_poller): - request = lro_retrys.build_put201_creating_succeeded200_request() - process = await (await get_poller(request)).result() - assert 'Succeeded' == process['properties']['provisioningState'] - - request = lro_retrys.build_put_async_relative_retry_succeeded_request() - process = await (await get_poller(request)).result() - assert 'Succeeded' == process['properties']['provisioningState'] - -@pytest.mark.asyncio -async def test_retrys_delete(get_poller, get_long_running_output_return_none): - request = lro_retrys.build_delete_provisioning202_accepted200_succeeded_request() - process = await (await get_poller(request)).result() - assert 'Succeeded' == process['properties']['provisioningState'] - - request = lro_retrys.build_delete202_retry200_request() - assert await (await get_poller(request, get_long_running_output=get_long_running_output_return_none)).result() is None - - request = lro_retrys.build_delete_async_relative_retry_succeeded_request() - assert await (await get_poller(request, get_long_running_output=get_long_running_output_return_none)).result() is None - -@pytest.mark.asyncio -async def test_retrys_post(get_poller, get_long_running_output_return_none): - request = lro_retrys.build_post202_retry200_request() - assert await (await get_poller(request, get_long_running_output=get_long_running_output_return_none)).result() is None - - request = lro_retrys.build_post_async_relative_retry_succeeded_request() - assert await (await get_poller(request, get_long_running_output=get_long_running_output_return_none)).result() is None - -@pytest.mark.skip(reason="https://github.com/Azure/azure-sdk-for-python/issues/17757") -@pytest.mark.asyncio -async def test_custom_headers_put_async_retry_succeeded(get_poller, custom_headers): - request = lr_os_custom_header.build_put_async_retry_succeeded_request(headers=custom_headers) - assert await (await get_poller(request)).result() is not None - -@pytest.mark.skip(reason="https://github.com/Azure/azure-sdk-for-python/issues/17757") -@pytest.mark.asyncio -async def test_custom_headers_post_async_retry_succeeded(get_poller, custom_headers): - request = lr_os_custom_header.build_post_async_retry_succeeded_request(headers=custom_headers) - assert await (await get_poller(request)).result() is None - -@pytest.mark.skip(reason="https://github.com/Azure/azure-sdk-for-python/issues/17757") -@pytest.mark.asyncio -async def test_custom_headers_put201_creating_succeeded200(get_poller, custom_headers): - request = lr_os_custom_header.build_put201_creating_succeeded200_request(headers=custom_headers) - assert await (await get_poller(request)).result() is not None - -@pytest.mark.skip(reason="https://github.com/Azure/azure-sdk-for-python/issues/17757") -@pytest.mark.asyncio -async def test_custom_headers_post202_retry200(get_poller, custom_headers): - request = lr_os_custom_header.build_post202_retry200_request(headers=custom_headers) - assert await (await get_poller(request)).result() is None - -@pytest.mark.asyncio -async def test_sads_put_non_retry(assert_initial_call_raises_with_message, assert_polling_raises_with_message): - request = lrosads.build_put_non_retry400_request() - await assert_initial_call_raises_with_message(request, "Bad Request") - - request = lrosads.build_put_non_retry201_creating400_request() - await assert_polling_raises_with_message(request, "Error from the server") - -@pytest.mark.asyncio -async def test_sads_put_async_relative(assert_polling_raises_with_message): - request = lrosads.build_put_async_relative_retry400_request() - await assert_polling_raises_with_message(request, "Operation returned an invalid status 'Bad Request'") - - request = lrosads.build_put_async_relative_retry_no_status_request() - await assert_polling_raises_with_message(request, "no status found in body") - - request = lrosads.build_put_async_relative_retry_no_status_payload_request() - await assert_polling_raises_with_message(request, "The response from long running operation does not contain a body.") - -@pytest.mark.asyncio -async def test_sads_put_error201_no_provisioning_state_payload(assert_polling_raises_with_message): - request = lrosads.build_put_error201_no_provisioning_state_payload_request() - await assert_polling_raises_with_message(request, "The response from long running operation does not contain a body.") - -@pytest.mark.asyncio -async def test_sads_put200_invalid_json_with_exception(get_poller): - request = lrosads.build_put200_invalid_json_request() - with pytest.raises(DecodeError): - await (await get_poller(request)).wait() - -@pytest.mark.skip(reason="The reason this fails is bc the convenience layer fails in deserializing the response headers. LLC doesn't do that, so skipping") -@pytest.mark.asyncio -async def test_sads_put_async_relative_with_exception(get_poller): - request = lrosads.build_put_async_relative_retry_invalid_json_polling_request() - with pytest.raises(DecodeError): - await (await get_poller(request)).wait() - - request = lrosads.build_put_async_relative_retry_invalid_header_request() - with pytest.raises(Exception): - await (await get_poller(request)).wait() - -@pytest.mark.asyncio -async def test_sads_put_non_retry201_creating400_invalid_json_with_exception(get_poller): - request = lrosads.build_put_non_retry201_creating400_invalid_json_request() - with pytest.raises(DecodeError): - await (await get_poller(request)).wait() - -@pytest.mark.asyncio -async def tests_lro_sads_delete_non_retry(assert_initial_call_raises_with_message, assert_polling_raises_with_message): - request = lrosads.build_delete_non_retry400_request() - await assert_initial_call_raises_with_message(request, "Bad Request") - - request = lrosads.build_delete202_non_retry400_request() - await assert_polling_raises_with_message(request, "Bad Request") - -@pytest.mark.asyncio -async def test_sads_delete_async_relative(assert_polling_raises_with_message): - request = lrosads.build_delete_async_relative_retry400_request() - await assert_polling_raises_with_message(request, "Bad Request") - - request = lrosads.build_delete_async_relative_retry_no_status_request() - await assert_polling_raises_with_message(request, "no status found in body") - -@pytest.mark.asyncio -async def test_sads_delete204_succeeded(get_poller): - request = lrosads.build_delete204_succeeded_request() - await (await get_poller(request)).wait() - -@pytest.mark.skip(reason="The reason this fails is bc the convenience layer fails in deserializing the retry-after header /bar as an int. LLC doesn't do that, so skipping") -@pytest.mark.asyncio -async def test_sads_delete_async_relative_with_exception(get_poller): - request = lrosads.build_delete_async_relative_retry_invalid_header_request() - with pytest.raises(Exception): - await (await get_poller(request)).wait() - - request = lrosads.build_delete_async_relative_retry_invalid_json_polling_request() - with pytest.raises(DecodeError): - await (await get_poller(request)).wait() - -@pytest.mark.skip(reason="The reason this fails is bc the convenience layer fails in deserializing the retry-after header /bar as an int. LLC doesn't do that, so skipping") -@pytest.mark.asyncio -async def test_sads_delete202_retry_invalid_header_with_exception(get_poller): - request = lrosads.build_delete202_retry_invalid_header_request() - with pytest.raises(Exception): - await (await get_poller(request)).wait() - -@pytest.mark.asyncio -async def test_sads_post_non_retry(assert_initial_call_raises_with_message, assert_polling_raises_with_message): - request = lrosads.build_post_non_retry400_request() - await assert_initial_call_raises_with_message(request, "Bad Request") - - request = lrosads.build_post202_non_retry400_request() - await assert_polling_raises_with_message(request, "Bad Request") - -@pytest.mark.asyncio -async def test_sads_post_async_relative(assert_polling_raises_with_message): - request = lrosads.build_post_async_relative_retry400_request() - await assert_polling_raises_with_message(request, "Bad Request") - - request = lrosads.build_post_async_relative_retry_no_payload_request() - await assert_polling_raises_with_message(request, "The response from long running operation does not contain a body.") - -@pytest.mark.asyncio -async def test_sads_post202_no_location(get_poller): - # Testserver wants us to fail (coverage name is LROErrorPostNoLocation) - # Actually, Python will NOT, and consider any kind of success 2xx on the initial call - # is an actual success - request = lrosads.build_post202_no_location_request() - process = await (await get_poller(request)).result() - assert process is None - -@pytest.mark.skip(reason="The reason this fails is bc the convenience layer fails in deserializing the retry-after header /bar as an int. LLC doesn't do that, so skipping") -@pytest.mark.asyncio -async def test_sads_post_async_relative_with_exception(get_poller): - request = lrosads.build_post_async_relative_retry_invalid_header_request() - with pytest.raises(Exception): - await (await get_poller(request)).wait() - - request = lrosads.build_post_async_relative_retry_invalid_json_polling_request() - - with pytest.raises(DecodeError): - await (await get_poller(request)).wait() - -@pytest.mark.skip(reason="The reason this fails is bc the convenience layer fails in deserializing the retry-after header /bar as an int. LLC doesn't do that, so skipping") -@pytest.mark.asyncio -async def test_post202_retry_invalid_header_with_exception(get_poller): - request = lrosads.build_post202_retry_invalid_header_request() - with pytest.raises(Exception): - await (await get_poller(request)).wait() - -@pytest.mark.asyncio -async def test_polling_interval_operation(get_poller): - default_polling_interval_start_time = time.time() - request = lros.build_post_double_headers_final_azure_header_get_default_request() - product1 = await (await get_poller(request)).result() - default_polling_interval_duration = time.time() - default_polling_interval_start_time - assert abs(default_polling_interval_duration - 0) < 0.1 - - one_second_polling_interval_start_time = time.time() - request = lros.build_post_double_headers_final_azure_header_get_default_request() - - product2 = await (await get_poller(request, polling_interval=1)).result() - one_second_polling_interval_duration = time.time() - one_second_polling_interval_start_time - assert abs(one_second_polling_interval_duration - 1) < 0.1 - - assert product1 == product2 - -@pytest.mark.asyncio -async def test_passing_kwargs(get_poller): - request = lros.build_put200_succeeded_request(headers={"Content-Type": "application/json"}) - process = await (await get_poller(request)).result() - assert "Succeeded" == process['properties']['provisioningState'] - -@pytest.mark.asyncio -async def test_lro_list(get_poller): - request = lros.build_post202_list_request() - products = await (await get_poller(request)).result() - assert len(products) == 1 - product = products[0] - assert product['id'] == "100" - assert product['name'] == "foo" - -@pytest.mark.asyncio -async def test_patch201_retry_with_async_header(get_poller, product): - request = lros.build_patch201_retry_with_async_header_request(json=product) - product = await (await get_poller(request)).result() - 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(get_poller, product): - request = lros.build_patch202_retry_with_async_and_location_header_request(json=product) - product = await (await get_poller(request)).result() - assert product == { "properties": { "provisioningState": "Succeeded"}, "id": "/lro/patch/202/retry/asyncAndLocationHeader", "name": "foo" } diff --git a/test/azure/low-level/AcceptanceTests/asynctests/test_paging.py b/test/azure/low-level/AcceptanceTests/asynctests/test_paging.py deleted file mode 100644 index 06af09b6099..00000000000 --- a/test/azure/low-level/AcceptanceTests/asynctests/test_paging.py +++ /dev/null @@ -1,348 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import functools -from async_generator import yield_, async_generator - -from paginglowlevel.aio import AutoRestPagingTestService -from paginglowlevel.rest import paging -from paginglowlevel._serialization import Serializer, Deserializer -from azure.core.async_paging import AsyncItemPaged, AsyncList -from azure.core.exceptions import HttpResponseError -from azure.core.pipeline.policies import ContentDecodePolicy, AsyncRetryPolicy, HeadersPolicy, RequestIdPolicy - -import pytest - -@pytest.fixture -@async_generator -async def client(cookie_policy): - policies = [ - RequestIdPolicy(), - HeadersPolicy(), - ContentDecodePolicy(), - AsyncRetryPolicy(), - cookie_policy - ] - async with AutoRestPagingTestService(policies=policies) as client: - await yield_(client) - -@pytest.fixture -def extract_data_fixture(deserializer): - async def _callback(pipeline_response, **kwargs): - item_name = kwargs.pop("item_name", "value") - next_link_name = kwargs.pop("next_link_name", "nextLink") - try: - deserialized = pipeline_response.http_response.json() # in the case of LRO + paging, the LRO returns an old response to us - except AttributeError: - deserialized = deserializer("object", pipeline_response.http_response) - list_of_elem = deserialized[item_name] - return deserialized.get(next_link_name, None), AsyncList(list_of_elem) - return _callback - -@pytest.fixture -def get_next_fixture(client): - async def _callback(prepare_request, next_link=None): - request = prepare_request(next_link) - - request.url = client._client.format_url(request.url) - pipeline_response = await client._client._pipeline.run(request) - pipeline_response.http_response.raise_for_status() - - return pipeline_response - return _callback - -def default_prepare_request(next_link=None, **kwargs): - initial_request = kwargs.pop("initial_request") - next_request = kwargs.pop("next_request", None) - if not next_link: - request = initial_request() - elif next_request: - try: - request = next_request(next_link) - except TypeError: - request = next_request() # the query one doesn't take next link - else: - request = initial_request() - request.url = next_link - return request - -@pytest.fixture -def get_pager(get_next_fixture, extract_data_fixture): - def _callback(initial_request, **kwargs): - prepare_request = functools.partial( - default_prepare_request, - initial_request=initial_request, - **kwargs - ) - get_next = functools.partial( - get_next_fixture, - prepare_request, - ) - extract_data = kwargs.pop("extract_data", None) - if not extract_data: - extract_data = functools.partial( - extract_data_fixture, - **kwargs - ) - - return AsyncItemPaged(get_next, extract_data) - return _callback - -@pytest.fixture() -def serializer(): - return Serializer() - -@pytest.fixture() -def deserializer(): - return Deserializer() - -@pytest.mark.asyncio -async def test_get_no_item_name_pages(get_pager): - pages = get_pager(initial_request=paging.build_get_no_item_name_pages_request) - items = [] - async for page in pages: - items.append(page) - assert len(items) == 1 - assert items[0]['properties']['id'] == 1 - assert items[0]['properties']['name'] == "Product" - -@pytest.mark.asyncio -async def test_get_null_next_link_name_pages(get_pager): - async def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized['values'] - # defined as None next link in swagger - return None, AsyncList(list_of_elem) - pages = get_pager( - initial_request=paging.build_get_null_next_link_name_pages_request, - item_name="values", - extract_data=extract_data - ) - items = [] - async for page in pages: - items.append(page) - assert len(items) == 1 - assert items[0]['properties']['id'] == 1 - assert items[0]['properties']['name'] == "Product" - -@pytest.mark.asyncio -async def test_get_single_pages(get_pager): - pages = get_pager(initial_request=paging.build_get_single_pages_request, item_name="values") - items = [] - async for page in pages: - items.append(page) - assert len(items) == 1 - assert items[0]['properties']['id'] == 1 - assert items[0]['properties']['name'] == "Product" - -@pytest.mark.asyncio -async def test_get_multiple_pages(get_pager): - pages = get_pager(initial_request=paging.build_get_multiple_pages_request, item_name="values") - items = [] - async for page in pages: - items.append(page) - assert len(items) == 10 - -@pytest.mark.asyncio -async def test_query_params(get_pager): - initial_request = functools.partial( - paging.build_get_with_query_params_request, - required_query_parameter='100' - ) - pages = get_pager( - initial_request=initial_request, - next_request=paging.build_next_operation_with_query_params_request, - item_name="values" - ) - items = [] - async for page in pages: - items.append(page) - assert len(items) == 2 - -@pytest.mark.asyncio -async def test_get_odata_multiple_pages(get_pager): - pages = get_pager( - initial_request=paging.build_get_odata_multiple_pages_request, - item_name="values", - next_link_name="odata.nextLink", - ) - items = [] - async for page in pages: - items.append(page) - assert len(items) == 10 - -@pytest.mark.asyncio -async def test_get_multiple_pages_retry_first(get_pager): - pages = get_pager( - initial_request=paging.build_get_multiple_pages_retry_first_request, - item_name="values", - ) - items = [] - async for page in pages: - items.append(page) - assert len(items) == 10 - -@pytest.mark.asyncio -async def test_get_multiple_pages_retry_second(get_pager): - pages = get_pager( - initial_request=paging.build_get_multiple_pages_retry_second_request, - item_name="values", - ) - items = [] - async for page in pages: - items.append(page) - assert len(items) == 10 - -@pytest.mark.asyncio -async def test_get_multiple_pages_with_offset(get_pager): - initial_request = functools.partial( - paging.build_get_multiple_pages_with_offset_request, - 100, - ) - pages = get_pager( - initial_request=initial_request, - item_name="values" - ) - items = [] - async for page in pages: - items.append(page) - assert len(items) == 10 - assert items[-1]['properties']['id'] == 110 - - -@pytest.mark.asyncio -async def test_get_single_pages_failure(get_pager): - pages = get_pager( - initial_request=paging.build_get_single_pages_failure_request, - item_name="values" - ) - with pytest.raises(HttpResponseError): - async for page in pages: - print(page) - -@pytest.mark.asyncio -async def test_get_multiple_pages_failure(get_pager): - pages = get_pager( - initial_request=paging.build_get_multiple_pages_failure_request, - item_name="values" - ) - with pytest.raises(HttpResponseError): - async for page in pages: - print(page) - -@pytest.mark.asyncio -async def test_get_multiple_pages_failure_uri(get_pager): - pages = get_pager( - initial_request=paging.build_get_multiple_pages_failure_uri_request, - item_name="values" - ) - with pytest.raises(HttpResponseError): - async for page in pages: - print(page) - -@pytest.mark.asyncio -async def test_paging_fragment_path(get_pager): - initial_request = functools.partial( - paging.build_get_multiple_pages_fragment_next_link_request, - "test_user", - api_version="1.6" - ) - next_request = functools.partial( - paging.build_next_fragment_request, - "test_user", - api_version="1.6" - ) - pages = get_pager( - initial_request=initial_request, - next_request=next_request, - item_name="values", - next_link_name="odata.nextLink", - ) - items = [] - async for page in pages: - items.append(page) - assert len(items) == 10 - - with pytest.raises(AttributeError): - # Be sure this method is not generated (Transform work) - paging.build_get_multiple_pages_fragment_next_link_next_request - -@pytest.mark.skip(reason="Can't figure this out yet, going to add later") -@pytest.mark.asyncio -async def test_get_multiple_pages_lro(client, get_next_fixture, extract_data_fixture): - """LRO + Paging at the same time. - """ - from azure.mgmt.core.polling.arm_polling import ARMPolling - from azure.core.polling import LROPoller - # initial LRO call - pipeline_response = await client._client._pipeline.run( - paging.build_get_multiple_pages_lro_request(), - ) - pipeline_response.http_response.raise_for_status() - prepare_request = functools.partial( - default_prepare_request, - initial_request=paging.build_get_multiple_pages_lro_request, - ) - def get_long_running_output(pipeline_response): - def internal_get_next(next_link=None): - if next_link is None: - return pipeline_response - else: - return get_next_fixture(prepare_request, next_link) - extract_data = functools.partial( - extract_data_fixture, - item_name="values" - ) - return AsyncItemPaged(internal_get_next, extract_data) - - polling_method = ARMPolling(timeout=0) - poller = LROPoller(client._client, pipeline_response, get_long_running_output, polling_method) - pager = poller.result() - - # paging calls - items = list(pager) - - assert len(items) == 10 - assert items[0]['properties']['id'] == 1 - assert items[1]['properties']['id'] == 2 - -@pytest.mark.asyncio -async def test_initial_response_no_items(get_pager): - pages = get_pager( - paging.build_first_response_empty_request, - ) - items = [] - async for page in pages: - items.append(page) - assert len(items) == 1 - -@pytest.mark.asyncio -async def test_duplicate_params(get_pager): - pages = get_pager( - initial_request=functools.partial(paging.build_duplicate_params_request, filter="foo"), - item_name="values" - ) - items = [i async for i in pages] - assert len(items) == 1 diff --git a/test/azure/low-level/AcceptanceTests/asynctests/test_parameter.py b/test/azure/low-level/AcceptanceTests/asynctests/test_parameter.py deleted file mode 100644 index 31b2d68d545..00000000000 --- a/test/azure/low-level/AcceptanceTests/asynctests/test_parameter.py +++ /dev/null @@ -1,237 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from async_generator import yield_, async_generator - -from azurespecialpropertieslowlevel.aio import AutoRestAzureSpecialParametersTestClient -from azurespecialpropertieslowlevel.rest import ( - skip_url_encoding, - subscription_in_credentials, - subscription_in_method, - api_version_default, - api_version_local, - odata, -) -from azureparametergroupinglowlevel.aio import AutoRestParameterGroupingTestService -from azureparametergroupinglowlevel.rest import parameter_grouping - -import pytest - -@pytest.fixture -def valid_subscription(): - return '1234-5678-9012-3456' - -@pytest.fixture -@async_generator -async def client(valid_subscription, credential, authentication_policy): - async with AutoRestAzureSpecialParametersTestClient( - credential, valid_subscription, authentication_policy=authentication_policy - ) as client: - await yield_(client) - -@pytest.fixture -@async_generator -async def parameter_grouping_client(authentication_policy): - async with AutoRestParameterGroupingTestService( - ) as client: - await yield_(client) - -@pytest.fixture -def body_parameter(): - return 1234 - -@pytest.fixture -def header_parameter(): - return 'header' - -@pytest.fixture -def query_parameter(): - return 21 - -@pytest.fixture -def path_parameter(): - return 'path' - - -@pytest.fixture -def unencoded_path(): - return 'path1/path2/path3' - -@pytest.fixture -def unencoded_query(): - return 'value1&q2=value2&q3=value3' - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_parameter_grouping(parameter_grouping_client, base_send_request): - async def _send_request(request): - return await base_send_request(parameter_grouping_client, request) - return _send_request - -@pytest.mark.asyncio -async def test_post_all_required_parameters(send_request_parameter_grouping, body_parameter, header_parameter, query_parameter, path_parameter): - request = parameter_grouping.build_post_required_request( - path=path_parameter, - json=body_parameter, - query=query_parameter, - custom_header=header_parameter - ) - await send_request_parameter_grouping(request) - -@pytest.mark.asyncio -async def test_post_required_parameters_null_optional_parameters(send_request_parameter_grouping, body_parameter, path_parameter): - request = parameter_grouping.build_post_required_request( - path=path_parameter, - json=body_parameter, - query=None, - ) - await send_request_parameter_grouping(request) - -@pytest.mark.asyncio -async def test_post_required_parameters_with_null_required_property(path_parameter): - with pytest.raises(TypeError): - parameter_grouping.build_post_required_request() - -@pytest.mark.asyncio -async def test_post_all_optional(send_request_parameter_grouping, header_parameter, query_parameter): - request = parameter_grouping.build_post_optional_request( - custom_header=header_parameter, - query=query_parameter - ) - await send_request_parameter_grouping(request) - -@pytest.mark.asyncio -async def test_post_none_optional(send_request_parameter_grouping): - request = parameter_grouping.build_post_optional_request(query=None) - await send_request_parameter_grouping(request) - -@pytest.mark.asyncio -async def test_post_all_multi_param_groups(send_request_parameter_grouping, header_parameter, query_parameter): - request = parameter_grouping.build_post_multi_param_groups_request( - header_one=header_parameter, - query_one=query_parameter, - header_two="header2", - query_two=42, - ) - await send_request_parameter_grouping(request) - -@pytest.mark.asyncio -async def test_post_some_multi_param_groups(send_request_parameter_grouping, header_parameter): - request = parameter_grouping.build_post_multi_param_groups_request( - header_one=header_parameter, - query_two=42, - ) - await send_request_parameter_grouping(request) - -@pytest.mark.asyncio -async def test_post_shared_parameter_group_object(send_request_parameter_grouping, header_parameter): - request = parameter_grouping.build_post_shared_parameter_group_object_request( - header_one=header_parameter - ) - await send_request_parameter_grouping(request) - -@pytest.mark.asyncio -async def test_post_reserved_words(send_request_parameter_grouping): - request = parameter_grouping.build_post_reserved_words_request(from_parameter="bob", accept_parameter="yes") - await send_request_parameter_grouping(request) - -@pytest.mark.asyncio -async def test_subscription_in_credentials(send_request, valid_subscription): - # valid_api_version = '2.0' - request = subscription_in_credentials.build_post_method_global_not_provided_valid_request(subscription_id=valid_subscription) - await send_request(request) - request = subscription_in_credentials.build_post_method_global_valid_request(subscription_id=valid_subscription) - await send_request(request) - request = subscription_in_credentials.build_post_path_global_valid_request(subscription_id=valid_subscription) - await send_request(request) - request = subscription_in_credentials.build_post_swagger_global_valid_request(subscription_id=valid_subscription) - await send_request(request) - -@pytest.mark.asyncio -async def test_subscription_in_method(send_request, valid_subscription): - request = subscription_in_method.build_post_method_local_valid_request(valid_subscription) - await send_request(request) - request = subscription_in_method.build_post_path_local_valid_request(valid_subscription) - await send_request(request) - request = subscription_in_method.build_post_swagger_local_valid_request(valid_subscription) - await send_request(request) - with pytest.raises(ValueError): - request = subscription_in_method.build_post_method_local_null_request(None) - -@pytest.mark.asyncio -async def test_api_version_default(send_request): - request = api_version_default.build_get_method_global_not_provided_valid_request() - await send_request(request) - request = api_version_default.build_get_method_global_valid_request() - await send_request(request) - request = api_version_default.build_get_path_global_valid_request() - await send_request(request) - request = api_version_default.build_get_swagger_global_valid_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_api_version_local(send_request): - request = api_version_local.build_get_method_local_valid_request() - await send_request(request) - request = api_version_local.build_get_method_local_null_request() - await send_request(request) - request = api_version_local.build_get_path_local_valid_request() - await send_request(request) - request = api_version_local.build_get_swagger_local_valid_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_skip_url_encoding(send_request, unencoded_path, unencoded_query): - request = skip_url_encoding.build_get_method_path_valid_request(unencoded_path) - await send_request(request) - request = skip_url_encoding.build_get_path_valid_request(unencoded_path) - await send_request(request) - request = skip_url_encoding.build_get_swagger_path_valid_request() - await send_request(request) - request = skip_url_encoding.build_get_method_query_valid_request(q1=unencoded_query) - await send_request(request) - request = skip_url_encoding.build_get_path_query_valid_request(q1=unencoded_query) - await send_request(request) - request = skip_url_encoding.build_get_swagger_query_valid_request() - await send_request(request) - request = skip_url_encoding.build_get_method_query_null_request() - await send_request(request) - request = skip_url_encoding.build_get_method_query_null_request(q1=None) - await send_request(request) - -@pytest.mark.asyncio -async def test_azure_odata(send_request): - request = odata.build_get_with_filter_request(filter="id gt 5 and name eq 'foo'", top=10, orderby="id") - await send_request(request) - -@pytest.mark.asyncio -async def test_with_constant(send_request): - request = parameter_grouping.build_group_with_constant_request(grouped_constant="foo", grouped_parameter="bar") - await send_request(request) diff --git a/test/azure/low-level/AcceptanceTests/asynctests/test_xms.py b/test/azure/low-level/AcceptanceTests/asynctests/test_xms.py deleted file mode 100644 index 35ed1b9e08f..00000000000 --- a/test/azure/low-level/AcceptanceTests/asynctests/test_xms.py +++ /dev/null @@ -1,99 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from async_generator import yield_, async_generator -from azure.core.exceptions import HttpResponseError - -from azurespecialpropertieslowlevel.aio import AutoRestAzureSpecialParametersTestClient -from azurespecialpropertieslowlevel.rest import xms_client_request_id, header - -import pytest - - -@pytest.fixture -@async_generator -async def client(credential, authentication_policy): - valid_subscription = "1234-5678-9012-3456" - async with AutoRestAzureSpecialParametersTestClient( - credential, - valid_subscription, - authentication_policy=authentication_policy, - ) as client: - await yield_(client) - - -@pytest.fixture -@async_generator -async def client_no_request_id(credential, authentication_policy): - valid_subscription = "1234-5678-9012-3456" - async with AutoRestAzureSpecialParametersTestClient( - credential, - valid_subscription, - auto_request_id=False, - authentication_policy=authentication_policy, - ) as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request, **kwargs): - return await base_send_request(client, request, **kwargs) - return _send_request - - -@pytest.mark.asyncio -async def test_client_request_id_in_exception(send_request): - request = xms_client_request_id.build_get_request() - with pytest.raises(HttpResponseError): - await send_request(request) - -@pytest.mark.asyncio -async def test_xms_request_client_id_in_client_none(send_request): - request = xms_client_request_id.build_get_request() - await send_request(request, request_id=None) - -@pytest.mark.asyncio -async def test_xms_request_client_id_in_client(send_request): - request = xms_client_request_id.build_get_request() - await send_request(request, 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 - request = xms_client_request_id.build_param_get_request(x_ms_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") - response = await client_no_request_id.send_request(request) - response.raise_for_status() - -@pytest.mark.asyncio -async def test_xms_custom_named_request_id(send_request): - request = header.build_custom_named_request_id_request(foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") - await send_request(request) - -@pytest.mark.asyncio -async def test_xms_custom_named_request_id_parameter_group(send_request): - request = header.build_custom_named_request_id_param_grouping_request(foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") - await send_request(request) diff --git a/test/azure/low-level/AcceptanceTests/conftest.py b/test/azure/low-level/AcceptanceTests/conftest.py deleted file mode 100644 index 6fbf7e925e5..00000000000 --- a/test/azure/low-level/AcceptanceTests/conftest.py +++ /dev/null @@ -1,107 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import sys -import subprocess -import os -import signal -from os.path import dirname, realpath -from azure.core.pipeline.policies import SansIOHTTPPolicy -import pytest - - -cwd = dirname(realpath(__file__)) - -#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 - return subprocess.Popen(cmd) - - 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 -def terminate_server_process(process): - 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.""" - server = start_server_process() - yield - terminate_server_process(server) - -@pytest.fixture() -def base_send_request(): - def send_request(client, request, **kwargs): - response = client.send_request(request, **kwargs) - response.raise_for_status() - return response - return send_request - -@pytest.fixture() -def base_send_request_json_response(): - def send_request_json_response(client, request, **kwargs): - response = client.send_request(request, **kwargs) - response.raise_for_status() - return response.json() - return send_request_json_response - -class CookiePolicy(SansIOHTTPPolicy): - def __init__(self, *args, **kwargs): - self._current_cookie = None - - def on_request(self, request, **kwargs): - http_request = request.http_request - if self._current_cookie: - http_request.headers["Cookie"] = self._current_cookie - self._current_cookie = None - - def on_response(self, request, response, **kwargs): - http_response = response.http_response - - if "Set-Cookie" in http_response.headers: - self._current_cookie = http_response.headers["Set-Cookie"] - -@pytest.fixture() -def cookie_policy(): - return CookiePolicy() - - -@pytest.fixture() -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(): - return SansIOHTTPPolicy() diff --git a/test/azure/low-level/AcceptanceTests/test_azure_url.py b/test/azure/low-level/AcceptanceTests/test_azure_url.py deleted file mode 100644 index b0901382f18..00000000000 --- a/test/azure/low-level/AcceptanceTests/test_azure_url.py +++ /dev/null @@ -1,42 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from uuid import uuid4 - -from subscriptionidapiversionlowlevel import MicrosoftAzureTestUrl -from subscriptionidapiversionlowlevel.rest import group - -def test_azure_url(credential, authentication_policy): - - sub_id = str(uuid4()) - - with MicrosoftAzureTestUrl(credential, sub_id, authentication_policy=authentication_policy) as client: - request = group.build_get_sample_resource_group_request(subscription_id=sub_id, resource_group_name="testgroup101") - response = client.send_request(request) - response.raise_for_status() - response_json = response.json() - assert response_json['name'] == 'testgroup101' - assert response_json['location'] == "West US" diff --git a/test/azure/low-level/AcceptanceTests/test_config.py b/test/azure/low-level/AcceptanceTests/test_config.py deleted file mode 100644 index 081027ef4ac..00000000000 --- a/test/azure/low-level/AcceptanceTests/test_config.py +++ /dev/null @@ -1,56 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, ARMChallengeAuthenticationPolicy -# Head is azure-arm -from headlowlevel 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"} - ) - 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"}) - -def test_credential_scopes_default(credential): - with AutoRestHeadTestService(credential) as client: - 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: - assert client._config.credential_scopes == ["http://i-should-be-the-only-credential"] - -def test_authentication_policy_default(credential): - with AutoRestHeadTestService(credential) as client: - assert isinstance(client._config.authentication_policy, ARMChallengeAuthenticationPolicy) \ No newline at end of file diff --git a/test/azure/low-level/AcceptanceTests/test_duration.py b/test/azure/low-level/AcceptanceTests/test_duration.py deleted file mode 100644 index ab21923c3d6..00000000000 --- a/test/azure/low-level/AcceptanceTests/test_duration.py +++ /dev/null @@ -1,66 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import isodate -from datetime import timedelta - -from bodydurationlowlevel import AutoRestDurationTestService -from bodydurationlowlevel.rest import duration - -import pytest - -@pytest.fixture -def client(): - with AutoRestDurationTestService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_get_null_and_invalid(send_request, send_request_json_response): - request = duration.build_get_null_request() - assert send_request(request).text() == '' - - # in dpg, we don't raise deserialization error - request = duration.build_get_invalid_request() - with pytest.raises(isodate.ISO8601Error): - isodate.parse_duration(send_request_json_response(request)) - -def test_positive_duration(send_request, send_request_json_response): - request = duration.build_get_positive_duration_request() - response = isodate.parse_duration(send_request_json_response(request)) - assert response == isodate.Duration(4, 45005, 0, years=3, months=6) - delta = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) - request = duration.build_put_positive_duration_request(json=isodate.duration_isoformat(delta)) - send_request(request) diff --git a/test/azure/low-level/AcceptanceTests/test_head.py b/test/azure/low-level/AcceptanceTests/test_head.py deleted file mode 100644 index 30ee1200b62..00000000000 --- a/test/azure/low-level/AcceptanceTests/test_head.py +++ /dev/null @@ -1,63 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from headlowlevel import AutoRestHeadTestService -from headlowlevel.rest import http_success -from headexceptionslowlevel import AutoRestHeadExceptionTestService -from headexceptionslowlevel.rest import head_exception -from azure.core.exceptions import HttpResponseError - -import pytest - -def test_head(credential, authentication_policy): - with AutoRestHeadTestService(credential, authentication_policy=authentication_policy) as client: - request = http_success.build_head200_request() - response = client.send_request(request) - response.raise_for_status() - - request = http_success.build_head204_request() - response = client.send_request(request) - response.raise_for_status() - - request = http_success.build_head404_request() - response = client.send_request(request) - with pytest.raises(HttpResponseError): - response.raise_for_status() - -def test_head_exception(credential, authentication_policy): - with AutoRestHeadExceptionTestService(credential, authentication_policy=authentication_policy) as client: - request = head_exception.build_head200_request() - response = client.send_request(request) - response.raise_for_status() - - request = head_exception.build_head204_request() - response = client.send_request(request) - response.raise_for_status() - - request = head_exception.build_head404_request() - response = client.send_request(request) - with pytest.raises(HttpResponseError): - response.raise_for_status() diff --git a/test/azure/low-level/AcceptanceTests/test_lro.py b/test/azure/low-level/AcceptanceTests/test_lro.py deleted file mode 100644 index e4fd0173fed..00000000000 --- a/test/azure/low-level/AcceptanceTests/test_lro.py +++ /dev/null @@ -1,561 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import time - -from azure.core.exceptions import DecodeError, HttpResponseError -from azure.core.pipeline.policies import ContentDecodePolicy, RetryPolicy, HeadersPolicy, RequestIdPolicy -from azure.core.pipeline.transport import HttpRequest -from azure.mgmt.core.polling.arm_polling import ARMPolling - -from lrolowlevel import AutoRestLongRunningOperationTestService -from lrolowlevel.rest import lr_os_custom_header, lro_retrys, lros, lrosads -from lrolowlevel._serialization import Serializer, Deserializer -from azure.core.polling import LROPoller, NoPolling - -try: - from urlparse import urlparse -except ImportError: - from urllib.parse import urlparse - -import pytest - -POLLING_INTERVAL = 0 - -class AutorestTestARMPolling(ARMPolling): - - def _polling_cookie(self, response): - """Collect retry cookie - we only want to do this for the test server - at this point, unless we implement a proper cookie policy. - - :returns: Dictionary containing a cookie header if required, - 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', '')} - 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() - 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: - 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'} - -def lro_result(func, *args, **kwargs): - if "polling" not in kwargs: - kwargs["polling"] = AutorestTestARMPolling(0) - return func(*args, **kwargs).result() - -@pytest.fixture -def get_long_running_output(deserializer): - # this is the default deserializer, just returns deserialized object - def _callback(pipeline_response): - return deserializer("object", pipeline_response.http_response) - return _callback - -@pytest.fixture -def get_long_running_output_return_none(): - # for use if the swagger has no defined return object, so we - # follow the convenience layer, and just return none - def _callback(pipeline_response): - return None - return _callback - -@pytest.fixture -def get_poller(get_long_running_output, client): - - def _callback(request, **kwargs): - request.url = client._client.format_url(request.url) - pipeline_response = client._client._pipeline.run(request) - pipeline_response.http_response.raise_for_status() - polling = kwargs.pop("polling", True) - deserializer = kwargs.pop("get_long_running_output", get_long_running_output) - polling_method = kwargs.pop("polling_method", None) - if not polling_method: - polling_method = AutorestTestARMPolling(kwargs.pop("polling_interval", 0)) if polling else NoPolling() - return LROPoller(client._client, pipeline_response, deserializer, polling_method) - return _callback - -def _check_message_in_error(ex, message): - try: - assert ex.value.message.lower() == message.lower() - except AssertionError: - assert message.lower() in ex.value.message.lower() - -@pytest.fixture -def assert_polling_raises_with_message(get_poller): - def _callback(request, message, **kwargs): - poller = get_poller(request, **kwargs) - with pytest.raises(HttpResponseError) as ex: - poller.result() - _check_message_in_error(ex, message) - return _callback - -@pytest.fixture -def assert_initial_call_raises_with_message(get_poller): - def _callback(request, message, **kwargs): - with pytest.raises(HttpResponseError) as ex: - get_poller(request, **kwargs) # this makes the initial call - _check_message_in_error(ex, message) - return _callback - -@pytest.fixture() -def serializer(): - return Serializer() - -@pytest.fixture() -def deserializer(): - return Deserializer() - -def test_post_double_headers_final_continuation_token(client, get_poller, get_long_running_output): - request = lros.build_post_double_headers_final_location_get_request() - - poller = get_poller(request) - continuation_token = poller.continuation_token() - - poller = LROPoller.from_continuation_token( - polling_method=ARMPolling(0), - continuation_token=continuation_token, - client=client._client, - deserialization_callback=get_long_running_output, - ) - product = poller.result() - assert product['id'] == "100" - -def test_post_double_headers_final(get_poller): - request = lros.build_post_double_headers_final_location_get_request() - poller = get_poller(request) - product = poller.result() - assert product['id'] == "100" - - request = lros.build_post_double_headers_final_azure_header_get_request() - polling_method = AutorestTestARMPolling(0, lro_options={"final-state-via": "azure-async-operation"}) - product = get_poller(request, polling_method=polling_method).result() - assert product['id'] == "100" - -def test_post_double_headers_default(get_poller): - # This test will work as long as the default is Location - request = lros.build_post_double_headers_final_azure_header_get_default_request() - product = get_poller(request).result() - assert product['id'] == "100" - -def test_happy_put201_creating_succeeded200(get_poller): - request = lros.build_put201_creating_succeeded200_request() - process = get_poller(request).result() - assert "Succeeded" == process['properties']['provisioningState'] - - # Testing nopolling - request = lros.build_put201_creating_succeeded200_request() - process = get_poller(request, polling=False).result() - assert "Creating" == process['properties']['provisioningState'] - -def test_happy_put201_creating_failed200(assert_polling_raises_with_message, get_poller): - request = lros.build_put201_creating_failed200_request() - assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - - request = lros.build_put201_creating_failed200_request() - process = get_poller(request, polling=False).result() - assert "Created" == process['properties']['provisioningState'] - -def test_happy_put200_updating_succeeded204(get_poller): - request = lros.build_put200_updating_succeeded204_request() - process = get_poller(request).result() - assert "Succeeded" == process['properties']['provisioningState'] - - process = get_poller(request, polling=False).result() - assert "Updating" == process['properties']['provisioningState'] - -def test_happy_put200_acceptedcanceled200(get_poller, assert_polling_raises_with_message): - request = lros.build_put200_acceptedcanceled200_request() - assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - - request = lros.build_put200_acceptedcanceled200_request() - process = get_poller(request, polling=False).result() - assert "Accepted" == process['properties']['provisioningState'] - -def test_happy_put_no_header_in_retry(get_poller): - request = lros.build_put_no_header_in_retry_request() - process = get_poller(request).result() - assert "Succeeded" == process['properties']['provisioningState'] - - request = lros.build_put_async_no_header_in_retry_request() - process = get_poller(request).result() - assert "Succeeded" == process['properties']['provisioningState'] - -def test_happy_put_sub_resource(get_poller): - request = lros.build_put_sub_resource_request() - process = get_poller(request).result() - assert "Succeeded" == process['properties']['provisioningState'] - - request = lros.build_put_async_sub_resource_request() - process = get_poller(request).result() - assert "Succeeded" == process['properties']['provisioningState'] - -def test_happy_put_non_resource(get_poller): - request = lros.build_put_non_resource_request() - process = get_poller(request).result() - assert "100" == process['id'] - - request = lros.build_put_async_non_resource_request() - process = get_poller(request).result() - assert "100" == process['id'] - -def test_happy_put200_succeeded(get_poller): - request = lros.build_put200_succeeded_request() - process = get_poller(request).result() - assert "Succeeded" == process['properties']['provisioningState'] - - request = lros.build_put200_succeeded_no_state_request() - process = get_poller(request).result() - assert "100" == process['id'] - -def test_put201_succeeded(get_poller): - request = lros.build_put201_succeeded_request() - process = get_poller(request).result() - - assert "Succeeded" == process['properties']['provisioningState'] - assert "100" == process['id'] - assert "foo" == process['name'] - -def test_happy_put202_retry200(get_poller): - request = lros.build_put202_retry200_request() - process = get_poller(request).result() - assert "100" == process['id'] - -def test_happy_put_retry_succeeded(get_poller): - request = lros.build_put_async_retry_succeeded_request() - process = get_poller(request).result() - assert "Succeeded" == process['properties']['provisioningState'] - - request = lros.build_put_async_no_retry_succeeded_request() - process = get_poller(request).result() - assert "Succeeded" == process['properties']['provisioningState'] - -def test_happy_put_retry_failed_canceled(get_poller, assert_polling_raises_with_message): - request = lros.build_put_async_retry_failed_request() - assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - - request = lros.build_put_async_no_retrycanceled_request() - assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - -def test_post202_retry200(get_poller, get_long_running_output_return_none): - request = lros.build_post202_retry200_request() - process = get_poller(request, get_long_running_output=get_long_running_output_return_none).result() - assert process is None - -def test_happy_delete(get_poller): - request = lros.build_delete204_succeeded_request() - assert get_poller(request).result() is None - - request = lros.build_delete202_retry200_request() - assert get_poller(request).result() is None - - request = lros.build_delete202_no_retry204_request() - assert get_poller(request).result() is None - -def test_happy_delete_no_header_in_retry(get_poller, get_long_running_output_return_none): - request = lros.build_delete_no_header_in_retry_request() - assert get_poller(request).result() is None - - request = lros.build_delete_async_no_header_in_retry_request() - assert get_poller(request, get_long_running_output=get_long_running_output_return_none).result() is None - -def test_happy_delete_async_retry_failed_canceled(assert_polling_raises_with_message): - request = lros.build_delete_async_retrycanceled_request() - assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - - request = lros.build_delete_async_retry_failed_request() - assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - -def test_happy_delete_async_succeeded(get_poller, get_long_running_output_return_none): - request = lros.build_delete_async_no_retry_succeeded_request() - assert get_poller(request, get_long_running_output=get_long_running_output_return_none).result() is None - - request = lros.build_delete_async_retry_succeeded_request() - assert get_poller(request, get_long_running_output=get_long_running_output_return_none).result() is None - -def test_happy_delete_provisioning(get_poller): - request = lros.build_delete_provisioning202_accepted200_succeeded_request() - process = get_poller(request).result() - assert "Succeeded" == process['properties']['provisioningState'] - - request = lros.build_delete_provisioning202_deletingcanceled200_request() - result = get_poller(request).result() - assert result['properties']['provisioningState'] == 'Canceled' - - request = lros.build_delete_provisioning202_deleting_failed200_request() - result = get_poller(request).result() - assert result['properties']['provisioningState'] == 'Failed' - -def test_happy_post(get_poller): - request = lros.build_post202_no_retry204_request() - assert get_poller(request).result() is None - - request = lros.build_post200_with_payload_request() - - sku = get_poller(request).result() - assert sku['id'] == '1' - -def test_happy_post_async_retry_failed_canceled(assert_polling_raises_with_message): - request = lros.build_post_async_retry_failed_request() - assert_polling_raises_with_message(request, "Internal Server Error") - - request = lros.build_post_async_retrycanceled_request() - assert_polling_raises_with_message(request, "Operation returned an invalid status 'OK'") - -def test_happy_post_async_succeeded(get_poller): - request = lros.build_post_async_retry_succeeded_request() - prod = get_poller(request).result() - assert prod['id'] == "100" - - request = lros.build_post_async_no_retry_succeeded_request() - prod = get_poller(request).result() - assert prod['id'] == "100" - -def test_retrys_put(get_poller): - request = lro_retrys.build_put201_creating_succeeded200_request() - process = get_poller(request).result() - assert 'Succeeded' == process['properties']['provisioningState'] - - request = lro_retrys.build_put_async_relative_retry_succeeded_request() - process = get_poller(request).result() - assert 'Succeeded' == process['properties']['provisioningState'] - -def test_retrys_delete(get_poller, get_long_running_output_return_none): - request = lro_retrys.build_delete_provisioning202_accepted200_succeeded_request() - process = get_poller(request).result() - assert 'Succeeded' == process['properties']['provisioningState'] - - request = lro_retrys.build_delete202_retry200_request() - assert get_poller(request, get_long_running_output=get_long_running_output_return_none).result() is None - - request = lro_retrys.build_delete_async_relative_retry_succeeded_request() - assert get_poller(request, get_long_running_output=get_long_running_output_return_none).result() is None - -def test_retrys_post(get_poller, get_long_running_output_return_none): - request = lro_retrys.build_post202_retry200_request() - assert get_poller(request, get_long_running_output=get_long_running_output_return_none).result() is None - - request = lro_retrys.build_post_async_relative_retry_succeeded_request() - assert get_poller(request, get_long_running_output=get_long_running_output_return_none).result() is None - -@pytest.mark.skip(reason="https://github.com/Azure/azure-sdk-for-python/issues/17757") -def test_custom_headers_put_async_retry_succeeded(get_poller, custom_headers): - request = lr_os_custom_header.build_put_async_retry_succeeded_request(headers=custom_headers) - assert get_poller(request).result() is not None - -@pytest.mark.skip(reason="https://github.com/Azure/azure-sdk-for-python/issues/17757") -def test_custom_headers_post_async_retry_succeeded(get_poller, custom_headers): - request = lr_os_custom_header.build_post_async_retry_succeeded_request(headers=custom_headers) - assert get_poller(request).result() is None - -@pytest.mark.skip(reason="https://github.com/Azure/azure-sdk-for-python/issues/17757") -def test_custom_headers_put201_creating_succeeded200(get_poller, custom_headers): - request = lr_os_custom_header.build_put201_creating_succeeded200_request(headers=custom_headers) - assert get_poller(request).result() is not None - -@pytest.mark.skip(reason="https://github.com/Azure/azure-sdk-for-python/issues/17757") -def test_custom_headers_post202_retry200(get_poller, custom_headers): - request = lr_os_custom_header.build_post202_retry200_request(headers=custom_headers) - assert get_poller(request).result() is None - -def test_sads_put_non_retry(assert_initial_call_raises_with_message, assert_polling_raises_with_message): - request = lrosads.build_put_non_retry400_request() - assert_initial_call_raises_with_message(request, "Bad Request") - - request = lrosads.build_put_non_retry201_creating400_request() - assert_polling_raises_with_message(request, "Error from the server") - -def test_sads_put_async_relative(assert_polling_raises_with_message): - request = lrosads.build_put_async_relative_retry400_request() - assert_polling_raises_with_message(request, "Operation returned an invalid status 'Bad Request'") - - request = lrosads.build_put_async_relative_retry_no_status_request() - assert_polling_raises_with_message(request, "no status found in body") - - request = lrosads.build_put_async_relative_retry_no_status_payload_request() - assert_polling_raises_with_message(request, "The response from long running operation does not contain a body.") - -def test_sads_put_error201_no_provisioning_state_payload(assert_polling_raises_with_message): - request = lrosads.build_put_error201_no_provisioning_state_payload_request() - assert_polling_raises_with_message(request, "The response from long running operation does not contain a body.") - -def test_sads_put200_invalid_json_with_exception(get_poller): - request = lrosads.build_put200_invalid_json_request() - with pytest.raises(DecodeError): - get_poller(request).wait() - -@pytest.mark.skip(reason="The reason this fails is bc the convenience layer fails in deserializing the response headers. LLC doesn't do that, so skipping") -def test_sads_put_async_relative_with_exception(get_poller): - request = lrosads.build_put_async_relative_retry_invalid_json_polling_request() - with pytest.raises(DecodeError): - get_poller(request).wait() - - request = lrosads.build_put_async_relative_retry_invalid_header_request() - with pytest.raises(Exception): - get_poller(request).wait() - -def test_sads_put_non_retry201_creating400_invalid_json_with_exception(get_poller): - request = lrosads.build_put_non_retry201_creating400_invalid_json_request() - with pytest.raises(DecodeError): - get_poller(request).wait() - -def tests_lro_sads_delete_non_retry(assert_initial_call_raises_with_message, assert_polling_raises_with_message): - request = lrosads.build_delete_non_retry400_request() - assert_initial_call_raises_with_message(request, "Bad Request") - - request = lrosads.build_delete202_non_retry400_request() - assert_polling_raises_with_message(request, "Bad Request") - -def test_sads_delete_async_relative(assert_polling_raises_with_message): - request = lrosads.build_delete_async_relative_retry400_request() - assert_polling_raises_with_message(request, "Bad Request") - - request = lrosads.build_delete_async_relative_retry_no_status_request() - assert_polling_raises_with_message(request, "no status found in body") - -def test_sads_delete204_succeeded(get_poller): - request = lrosads.build_delete204_succeeded_request() - get_poller(request).wait() - -@pytest.mark.skip(reason="The reason this fails is bc the convenience layer fails in deserializing the retry-after header /bar as an int. LLC doesn't do that, so skipping") -def test_sads_delete_async_relative_with_exception(get_poller): - request = lrosads.build_delete_async_relative_retry_invalid_header_request() - with pytest.raises(Exception): - get_poller(request).wait() - - request = lrosads.build_delete_async_relative_retry_invalid_json_polling_request() - with pytest.raises(DecodeError): - get_poller(request).wait() - -@pytest.mark.skip(reason="The reason this fails is bc the convenience layer fails in deserializing the retry-after header /bar as an int. LLC doesn't do that, so skipping") -def test_sads_delete202_retry_invalid_header_with_exception(get_poller): - request = lrosads.build_delete202_retry_invalid_header_request() - with pytest.raises(Exception): - get_poller(request).wait() - -def test_sads_post_non_retry(assert_initial_call_raises_with_message, assert_polling_raises_with_message): - request = lrosads.build_post_non_retry400_request() - assert_initial_call_raises_with_message(request, "Bad Request") - - request = lrosads.build_post202_non_retry400_request() - assert_polling_raises_with_message(request, "Bad Request") - -def test_sads_post_async_relative(assert_polling_raises_with_message): - request = lrosads.build_post_async_relative_retry400_request() - assert_polling_raises_with_message(request, "Bad Request") - - request = lrosads.build_post_async_relative_retry_no_payload_request() - assert_polling_raises_with_message(request, "The response from long running operation does not contain a body.") - -def test_sads_post202_no_location(get_poller): - # Testserver wants us to fail (coverage name is LROErrorPostNoLocation) - # Actually, Python will NOT, and consider any kind of success 2xx on the initial call - # is an actual success - request = lrosads.build_post202_no_location_request() - process = get_poller(request).result() - assert process is None - -@pytest.mark.skip(reason="The reason this fails is bc the convenience layer fails in deserializing the retry-after header /bar as an int. LLC doesn't do that, so skipping") -def test_sads_post_async_relative_with_exception(get_poller): - request = lrosads.build_post_async_relative_retry_invalid_header_request() - with pytest.raises(Exception): - get_poller(request).wait() - - request = lrosads.build_post_async_relative_retry_invalid_json_polling_request() - - with pytest.raises(DecodeError): - get_poller(request).wait() - -@pytest.mark.skip(reason="The reason this fails is bc the convenience layer fails in deserializing the retry-after header /bar as an int. LLC doesn't do that, so skipping") -def test_post202_retry_invalid_header_with_exception(get_poller): - request = lrosads.build_post202_retry_invalid_header_request() - with pytest.raises(Exception): - get_poller(request).wait() - -def test_polling_interval_operation(get_poller): - default_polling_interval_start_time = time.time() - request = lros.build_post_double_headers_final_azure_header_get_default_request() - product1 = get_poller(request).result() - default_polling_interval_duration = time.time() - default_polling_interval_start_time - assert abs(default_polling_interval_duration - 0) < 0.1 - - one_second_polling_interval_start_time = time.time() - request = lros.build_post_double_headers_final_azure_header_get_default_request() - - product2 = get_poller(request, polling_interval=1).result() - one_second_polling_interval_duration = time.time() - one_second_polling_interval_start_time - assert abs(one_second_polling_interval_duration - 1) < 0.1 - - assert product1 == product2 - -def test_passing_kwargs(get_poller): - request = lros.build_put200_succeeded_request(headers={"Content-Type": "application/json"}) - process = get_poller(request).result() - assert "Succeeded" == process['properties']['provisioningState'] - -def test_lro_list(get_poller): - request = lros.build_post202_list_request() - products = get_poller(request).result() - assert len(products) == 1 - product = products[0] - assert product['id'] == "100" - assert product['name'] == "foo" - -def test_patch201_retry_with_async_header(get_poller, product): - request = lros.build_patch201_retry_with_async_header_request(json=product) - product = get_poller(request).result() - assert product == {"properties": {"provisioningState": "Succeeded"}, "id": "/lro/patch/201/retry/onlyAsyncHeader", "name": "foo"} - -def test_patch202_retry_with_async_and_location_header(get_poller, product): - request = lros.build_patch202_retry_with_async_and_location_header_request(json=product) - product = get_poller(request).result() - assert product == { "properties": { "provisioningState": "Succeeded"}, "id": "/lro/patch/202/retry/asyncAndLocationHeader", "name": "foo" } diff --git a/test/azure/low-level/AcceptanceTests/test_paging.py b/test/azure/low-level/AcceptanceTests/test_paging.py deleted file mode 100644 index 4ba1a48b246..00000000000 --- a/test/azure/low-level/AcceptanceTests/test_paging.py +++ /dev/null @@ -1,299 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import functools -import sys -from azure.core.rest import HttpRequest -from azure.core.paging import ItemPaged -from paginglowlevel import AutoRestPagingTestService -from paginglowlevel.rest import paging -from paginglowlevel._serialization import Serializer, Deserializer -from azure.core.exceptions import HttpResponseError - - -import pytest - -@pytest.fixture -def client(): - with AutoRestPagingTestService() as client: - yield client - -@pytest.fixture -def extract_data_fixture(deserializer): - def _callback(pipeline_response, **kwargs): - item_name = kwargs.pop("item_name", "value") - next_link_name = kwargs.pop("next_link_name", "nextLink") - try: - deserialized = pipeline_response.http_response.json() # in the case of LRO + paging, the LRO returns an old response to us - except AttributeError: - deserialized = deserializer("object", pipeline_response.http_response) - list_of_elem = deserialized[item_name] - return deserialized.get(next_link_name, None), iter(list_of_elem) - return _callback - -@pytest.fixture -def get_next_fixture(client): - def _callback(prepare_request, next_link=None): - request = prepare_request(next_link) - request.url = client._client.format_url(request.url) - pipeline_response = client._client._pipeline.run(request) - pipeline_response.http_response.raise_for_status() - - return pipeline_response - return _callback - -def default_prepare_request(next_link=None, **kwargs): - initial_request = kwargs.pop("initial_request") - next_request = kwargs.pop("next_request", None) - if not next_link: - request = initial_request() - elif next_request: - try: - request = next_request(next_link) - except TypeError: - request = next_request() # the query one doesn't take next link - else: - request = initial_request() - request.url = next_link - return request - -@pytest.fixture -def get_pager(get_next_fixture, extract_data_fixture): - def _callback(initial_request, **kwargs): - prepare_request = functools.partial( - default_prepare_request, - initial_request=initial_request, - **kwargs - ) - get_next = functools.partial( - get_next_fixture, - prepare_request, - ) - extract_data = kwargs.pop("extract_data", None) - if not extract_data: - extract_data = functools.partial( - extract_data_fixture, - **kwargs - ) - - return ItemPaged(get_next, extract_data) - return _callback - -@pytest.fixture() -def serializer(): - return Serializer() - -@pytest.fixture() -def deserializer(): - return Deserializer() - - -def test_get_no_item_name_pages(get_pager): - pages = get_pager(initial_request=paging.build_get_no_item_name_pages_request) - items = [i for i in pages] - assert len(items) == 1 - assert items[0]['properties']['id'] == 1 - assert items[0]['properties']['name'] == "Product" - -def test_get_null_next_link_name_pages(get_pager): - def extract_data(pipeline_response): - deserialized = pipeline_response.http_response.json() - list_of_elem = deserialized['values'] - # defined as None next link in swagger - return None, iter(list_of_elem) - pages = get_pager( - initial_request=paging.build_get_null_next_link_name_pages_request, - item_name="values", - extract_data=extract_data - ) - items = [i for i in pages] - assert len(items) == 1 - assert items[0]['properties']['id'] == 1 - assert items[0]['properties']['name'] == "Product" - -def test_get_single_pages(get_pager): - pages = get_pager(initial_request=paging.build_get_single_pages_request, item_name="values") - items = [i for i in pages] - assert len(items) == 1 - assert items[0]['properties']['id'] == 1 - assert items[0]['properties']['name'] == "Product" - -def test_get_multiple_pages(get_pager): - pages = get_pager(initial_request=paging.build_get_multiple_pages_request, item_name="values") - items = [i for i in pages] - assert len(items) == 10 - -def test_query_params(get_pager): - initial_request = functools.partial( - paging.build_get_with_query_params_request, - required_query_parameter='100' - ) - pages = get_pager( - initial_request=initial_request, - next_request=paging.build_next_operation_with_query_params_request, - item_name="values" - ) - items = [i for i in pages] - assert len(items) == 2 - -def test_get_odata_multiple_pages(get_pager): - pages = get_pager( - initial_request=paging.build_get_odata_multiple_pages_request, - item_name="values", - next_link_name="odata.nextLink", - ) - items = [i for i in pages] - assert len(items) == 10 - -def test_get_multiple_pages_retry_first(get_pager): - pages = get_pager( - initial_request=paging.build_get_multiple_pages_retry_first_request, - item_name="values", - ) - items = [i for i in pages] - assert len(items) == 10 - -def test_get_multiple_pages_retry_second(get_pager): - pages = get_pager( - initial_request=paging.build_get_multiple_pages_retry_second_request, - item_name="values", - ) - items = [i for i in pages] - assert len(items) == 10 - -def test_get_multiple_pages_with_offset(get_pager): - initial_request = functools.partial( - paging.build_get_multiple_pages_with_offset_request, - 100, - ) - pages = get_pager( - initial_request=initial_request, - item_name="values" - ) - items = [i for i in pages] - assert len(items) == 10 - assert items[-1]['properties']['id'] == 110 - - -def test_get_single_pages_failure(get_pager): - pages = get_pager( - initial_request=paging.build_get_single_pages_failure_request, - item_name="values" - ) - with pytest.raises(HttpResponseError): - list(pages) - -def test_get_multiple_pages_failure(get_pager): - pages = get_pager( - initial_request=paging.build_get_multiple_pages_failure_request, - item_name="values" - ) - with pytest.raises(HttpResponseError): - list(pages) - -def test_get_multiple_pages_failure_uri(get_pager): - pages = get_pager( - initial_request=paging.build_get_multiple_pages_failure_uri_request, - item_name="values" - ) - with pytest.raises(HttpResponseError): - list(pages) - -def test_paging_fragment_path(get_pager): - initial_request = functools.partial( - paging.build_get_multiple_pages_fragment_next_link_request, - "test_user", - api_version="1.6" - ) - next_request = functools.partial( - paging.build_next_fragment_request, - "test_user", - api_version="1.6" - ) - pages = get_pager( - initial_request=initial_request, - next_request=next_request, - item_name="values", - next_link_name="odata.nextLink", - ) - items = [i for i in pages] - assert len(items) == 10 - - with pytest.raises(AttributeError): - # Be sure this method is not generated (Transform work) - paging.build_get_multiple_pages_fragment_next_link_next_request - -@pytest.mark.skip(reason="Can't figure this out yet, going to add later") -def test_get_multiple_pages_lro(client, get_next_fixture, extract_data_fixture): - """LRO + Paging at the same time. - """ - from azure.mgmt.core.polling.arm_polling import ARMPolling - from azure.core.polling import LROPoller - # initial LRO call - pipeline_response = client._client._pipeline.run( - paging.build_get_multiple_pages_lro_request(), - ) - pipeline_response.http_response.raise_for_status() - prepare_request = functools.partial( - default_prepare_request, - initial_request=paging.build_get_multiple_pages_lro_request, - ) - def get_long_running_output(pipeline_response): - def internal_get_next(next_link=None): - if next_link is None: - return pipeline_response - else: - return get_next_fixture(prepare_request, next_link) - extract_data = functools.partial( - extract_data_fixture, - item_name="values" - ) - return ItemPaged(internal_get_next, extract_data) - - polling_method = ARMPolling(timeout=0) - poller = LROPoller(client._client, pipeline_response, get_long_running_output, polling_method) - pager = poller.result() - - # paging calls - items = list(pager) - - assert len(items) == 10 - assert items[0]['properties']['id'] == 1 - assert items[1]['properties']['id'] == 2 - -def test_initial_response_no_items(get_pager): - pages = get_pager( - paging.build_first_response_empty_request, - ) - items = [i for i in pages] - assert len(items) == 1 - -def test_duplicate_params(get_pager): - pages = get_pager( - initial_request=functools.partial(paging.build_duplicate_params_request, filter="foo"), - item_name="values" - ) - items = [i for i in pages] - assert len(items) == 1 diff --git a/test/azure/low-level/AcceptanceTests/test_parameter.py b/test/azure/low-level/AcceptanceTests/test_parameter.py deleted file mode 100644 index 61504f9f3a6..00000000000 --- a/test/azure/low-level/AcceptanceTests/test_parameter.py +++ /dev/null @@ -1,216 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from azurespecialpropertieslowlevel import AutoRestAzureSpecialParametersTestClient -from azurespecialpropertieslowlevel.rest import ( - skip_url_encoding, - subscription_in_credentials, - subscription_in_method, - api_version_default, - api_version_local, - odata, -) -from azureparametergroupinglowlevel import AutoRestParameterGroupingTestService -from azureparametergroupinglowlevel.rest import parameter_grouping - - -import pytest - -@pytest.fixture -def valid_subscription(): - return '1234-5678-9012-3456' - -@pytest.fixture -def client(valid_subscription, credential, authentication_policy): - with AutoRestAzureSpecialParametersTestClient(credential, valid_subscription, authentication_policy=authentication_policy) as client: - yield client - -@pytest.fixture -def parameter_grouping_client(): - with AutoRestParameterGroupingTestService() as client: - yield client - -@pytest.fixture -def body_parameter(): - return 1234 - -@pytest.fixture -def header_parameter(): - return 'header' - -@pytest.fixture -def query_parameter(): - return 21 - -@pytest.fixture -def path_parameter(): - return 'path' - - -@pytest.fixture -def unencoded_path(): - return 'path1/path2/path3' - -@pytest.fixture -def unencoded_query(): - return 'value1&q2=value2&q3=value3' - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_parameter_grouping(parameter_grouping_client, base_send_request): - def _send_request(request): - return base_send_request(parameter_grouping_client, request) - return _send_request - -def test_post_all_required_parameters(send_request_parameter_grouping, body_parameter, header_parameter, query_parameter, path_parameter): - request = parameter_grouping.build_post_required_request( - path=path_parameter, - json=body_parameter, - query=query_parameter, - custom_header=header_parameter - ) - send_request_parameter_grouping(request) - -def test_post_required_parameters_null_optional_parameters(send_request_parameter_grouping, body_parameter, path_parameter): - request = parameter_grouping.build_post_required_request( - path=path_parameter, - json=body_parameter, - query=None, - ) - send_request_parameter_grouping(request) - -def test_post_required_parameters_with_null_required_property(path_parameter): - with pytest.raises(TypeError): - parameter_grouping.build_post_required_request() - -def test_post_reserved_words(send_request_parameter_grouping): - request = parameter_grouping.build_post_reserved_words_request(from_parameter="bob", accept_parameter="yes") - send_request_parameter_grouping(request) - -def test_post_all_optional(send_request_parameter_grouping, header_parameter, query_parameter): - request = parameter_grouping.build_post_optional_request( - custom_header=header_parameter, - query=query_parameter - ) - send_request_parameter_grouping(request) - -def test_post_none_optional(send_request_parameter_grouping): - request = parameter_grouping.build_post_optional_request(query=None) - send_request_parameter_grouping(request) - -def test_post_all_multi_param_groups(send_request_parameter_grouping, header_parameter, query_parameter): - request = parameter_grouping.build_post_multi_param_groups_request( - header_one=header_parameter, - query_one=query_parameter, - header_two="header2", - query_two=42, - ) - send_request_parameter_grouping(request) - -def test_post_some_multi_param_groups(send_request_parameter_grouping, header_parameter): - request = parameter_grouping.build_post_multi_param_groups_request( - header_one=header_parameter, - query_two=42, - ) - send_request_parameter_grouping(request) - -def test_post_shared_parameter_group_object(send_request_parameter_grouping, header_parameter): - request = parameter_grouping.build_post_shared_parameter_group_object_request( - header_one=header_parameter - ) - send_request_parameter_grouping(request) - -def test_subscription_in_credentials(send_request, valid_subscription): - # valid_api_version = '2.0' - request = subscription_in_credentials.build_post_method_global_not_provided_valid_request(subscription_id=valid_subscription) - send_request(request) - request = subscription_in_credentials.build_post_method_global_valid_request(subscription_id=valid_subscription) - send_request(request) - request = subscription_in_credentials.build_post_path_global_valid_request(subscription_id=valid_subscription) - send_request(request) - request = subscription_in_credentials.build_post_swagger_global_valid_request(subscription_id=valid_subscription) - send_request(request) - -def test_subscription_in_method(send_request, valid_subscription): - request = subscription_in_method.build_post_method_local_valid_request(valid_subscription) - send_request(request) - request = subscription_in_method.build_post_path_local_valid_request(valid_subscription) - send_request(request) - request = subscription_in_method.build_post_swagger_local_valid_request(valid_subscription) - send_request(request) - with pytest.raises(ValueError): - request = subscription_in_method.build_post_method_local_null_request(None) - -def test_api_version_default(send_request): - request = api_version_default.build_get_method_global_not_provided_valid_request() - send_request(request) - request = api_version_default.build_get_method_global_valid_request() - send_request(request) - request = api_version_default.build_get_path_global_valid_request() - send_request(request) - request = api_version_default.build_get_swagger_global_valid_request() - send_request(request) - -def test_api_version_local(send_request): - request = api_version_local.build_get_method_local_valid_request() - send_request(request) - request = api_version_local.build_get_method_local_null_request() - send_request(request) - request = api_version_local.build_get_path_local_valid_request() - send_request(request) - request = api_version_local.build_get_swagger_local_valid_request() - send_request(request) - -def test_skip_url_encoding(send_request, unencoded_path, unencoded_query): - request = skip_url_encoding.build_get_method_path_valid_request(unencoded_path) - send_request(request) - request = skip_url_encoding.build_get_path_valid_request(unencoded_path) - send_request(request) - request = skip_url_encoding.build_get_swagger_path_valid_request() - send_request(request) - request = skip_url_encoding.build_get_method_query_valid_request(q1=unencoded_query) - send_request(request) - request = skip_url_encoding.build_get_path_query_valid_request(q1=unencoded_query) - send_request(request) - request = skip_url_encoding.build_get_swagger_query_valid_request() - send_request(request) - request = skip_url_encoding.build_get_method_query_null_request() - send_request(request) - request = skip_url_encoding.build_get_method_query_null_request(q1=None) - send_request(request) - -def test_azure_odata(send_request): - request = odata.build_get_with_filter_request(filter="id gt 5 and name eq 'foo'", top=10, orderby="id") - send_request(request) - -def test_with_constant(send_request): - request = parameter_grouping.build_group_with_constant_request(grouped_constant="foo", grouped_parameter="bar") - send_request(request) diff --git a/test/azure/low-level/AcceptanceTests/test_xms.py b/test/azure/low-level/AcceptanceTests/test_xms.py deleted file mode 100644 index b492e00702a..00000000000 --- a/test/azure/low-level/AcceptanceTests/test_xms.py +++ /dev/null @@ -1,90 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError - -from azurespecialpropertieslowlevel import AutoRestAzureSpecialParametersTestClient -from azurespecialpropertieslowlevel.rest import xms_client_request_id, header - -import pytest - - -@pytest.fixture -def client(credential, authentication_policy): - valid_subscription = "1234-5678-9012-3456" - with AutoRestAzureSpecialParametersTestClient( - credential, - valid_subscription, - authentication_policy=authentication_policy, - ) as client: - yield client - - -@pytest.fixture -def client_no_request_id(credential, authentication_policy): - valid_subscription = "1234-5678-9012-3456" - with AutoRestAzureSpecialParametersTestClient( - credential, - valid_subscription, - auto_request_id=False, - authentication_policy=authentication_policy, - ) as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request, **kwargs): - return base_send_request(client, request, **kwargs) - return _send_request - - -def test_client_request_id_in_exception(send_request): - request = xms_client_request_id.build_get_request() - with pytest.raises(HttpResponseError): - send_request(request) - -def test_xms_request_client_id_in_client_none(send_request): - request = xms_client_request_id.build_get_request() - send_request(request, request_id=None) - -def test_xms_request_client_id_in_client(send_request): - request = xms_client_request_id.build_get_request() - send_request(request, 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 - request = xms_client_request_id.build_param_get_request(x_ms_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") - response = client_no_request_id.send_request(request) - response.raise_for_status() - -def test_xms_custom_named_request_id(send_request): - request = header.build_custom_named_request_id_request(foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") - send_request(request) - -def test_xms_custom_named_request_id_parameter_group(send_request): - request = header.build_custom_named_request_id_param_grouping_request(foo_client_request_id="9C4D50EE-2D56-4CD3-8152-34347DC9F2B0") - send_request(request) diff --git a/test/azure/low-level/AcceptanceTests/test_zzz.py b/test/azure/low-level/AcceptanceTests/test_zzz.py deleted file mode 100644 index 56f12d53081..00000000000 --- a/test/azure/low-level/AcceptanceTests/test_zzz.py +++ /dev/null @@ -1,92 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import sys -import datetime -import os -import platform -import warnings - -from azurereportlowlevel import AutoRestReportServiceForAzure, rest - - -class TestAcceptance(object): - - def test_ensure_coverage(self): - client = AutoRestReportServiceForAzure() - request = rest.build_get_report_request(qualifier=platform.python_version()) - report = client.send_request(request).json() - - # Add tests that wont be supported due to the nature of Python here - not_supported = { - "LROConstantParameterizedPost": 1, # involves formatting base url - "LROConstantParameterizedGet": 1, # involves formatting base url - "CustomHeaderPutAsyncSucceded": 1, # waiting for https://github.com/Azure/azure-sdk-for-python/issues/17757 to be released - "CustomHeaderPostAsyncSucceded": 1, # waiting for https://github.com/Azure/azure-sdk-for-python/issues/17757 to be released - "CustomHeaderPutSucceeded": 1, # waiting for https://github.com/Azure/azure-sdk-for-python/issues/17757 to be released - "CustomHeaderPostSucceeded": 1, # waiting for https://github.com/Azure/azure-sdk-for-python/issues/17757 to be released - "PagingReturnModelWithXMSClientName": 1, # not relevant, we don't generate return models in LLC - "PagingCustomUrlPartialNextLink": 1, # involves formatting base url - "PagingCustomUrlPartialOperationNextLink": 1, # involves formatting base url - "LROParameterizedEndpoint": 1, # involves formatting base url - "LROErrorPutAsyncInvalidJsonPolling": 1, # The reason this fails is bc the convenience layer fails in deserializing the response headers. LLC doesn't do that, so skipping - "LROErrorPutAsyncInvalidHeader": 1, # The reason this fails is bc the convenience layer fails in deserializing the response headers. LLC doesn't do that, so skipping - "LROErrorDelete202RetryInvalidHeader": 1, # The reason this fails is bc the convenience layer fails in deserializing the response headers. LLC doesn't do that, so skipping - "LROErrorDeleteAsyncInvalidHeader": 1, # The reason this fails is bc the convenience layer fails in deserializing the response headers. LLC doesn't do that, so skipping - "LROErrorDeleteAsyncInvalidJsonPolling": 1, # The reason this fails is bc the convenience layer fails in deserializing the retry-after header /bar as an int. LLC doesn't do that, so skipping - "LROErrorPost202RetryInvalidHeader": 1, # The reason this fails is bc the convenience layer fails in deserializing the retry-after header /bar as an int. LLC doesn't do that, so skipping - "LROErrorPostAsyncInvalidHeader": 1, # The reason this fails is bc the convenience layer fails in deserializing the retry-after header /bar as an int. LLC doesn't do that, so skipping - "LROErrorPostAsyncInvalidJsonPolling": 1, # The reason this fails is bc the convenience layer fails in deserializing. LLC doesn't do that, so skipping - "LROPatchInlineCompleteIgnoreHeaders": 1, - } - - # Please add missing features or failing tests here - missing_features_or_bugs = { - "PagingMultipleLRO": 1, # can't quite figure it out, skipping for now bc low pri - } - - 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) - for s in not_supported.keys(): - print("IGNORING {0}".format(s)) - - if missing_features_or_bugs: - report.update(missing_features_or_bugs) - for s in missing_features_or_bugs.keys(): - print("PENDING {0}".format(s)) - - failed = [k for k, v in report.items() if v == 0] - for s in failed: - 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)) - - assert 0 == len(failed) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/__init__.py deleted file mode 100644 index 44c09782afe..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestDurationTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestDurationTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_client.py deleted file mode 100644 index cf207cd4ee4..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestDurationTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestDurationTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestDurationTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydurationlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydurationlowlevel.rest import duration - >>> request = duration.build_get_null_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestDurationTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_configuration.py deleted file mode 100644 index d3e575e957c..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestDurationTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestDurationTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestDurationTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestdurationtestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/__init__.py deleted file mode 100644 index a58fa28f613..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestDurationTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestDurationTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_client.py deleted file mode 100644 index 0570d4fbe93..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestDurationTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestDurationTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestDurationTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydurationlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydurationlowlevel.rest import duration - >>> request = duration.build_get_null_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestDurationTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_configuration.py deleted file mode 100644 index 029a04192bc..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestDurationTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestDurationTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestDurationTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestdurationtestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/duration/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/duration/__init__.py deleted file mode 100644 index 920665f48c7..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/duration/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_null_request -from ._request_builders import build_put_positive_duration_request -from ._request_builders import build_get_positive_duration_request -from ._request_builders import build_get_invalid_request - -__all__ = [ - "build_get_null_request", - "build_put_positive_duration_request", - "build_get_positive_duration_request", - "build_get_invalid_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/duration/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/duration/_request_builders.py deleted file mode 100644 index e178029cc3a..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/bodydurationlowlevel/rest/duration/_request_builders.py +++ /dev/null @@ -1,122 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null duration value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/duration/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_positive_duration_request(*, json: datetime.timedelta, **kwargs: Any) -> HttpRequest: - """Put a positive duration value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: duration body. Required. - :paramtype json: ~datetime.timedelta - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/duration/positiveduration" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_positive_duration_request(**kwargs: Any) -> HttpRequest: - """Get a positive duration value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/duration/positiveduration" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_request(**kwargs: Any) -> HttpRequest: - """Get an invalid duration value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/duration/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/setup.py deleted file mode 100644 index 0030e99261a..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureBodyDurationLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestdurationtestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestDurationTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/__init__.py deleted file mode 100644 index 4435057ee57..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterGroupingTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterGroupingTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_client.py deleted file mode 100644 index 64d5dbe8b2e..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestParameterGroupingTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterGroupingTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestParameterGroupingTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `azureparametergroupinglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from azureparametergroupinglowlevel.rest import parameter_grouping - >>> request = parameter_grouping.build_post_required_request(path, json=json, custom_header=custom_header, query=query, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestParameterGroupingTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_configuration.py deleted file mode 100644 index c623295dd8c..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestParameterGroupingTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterGroupingTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestParameterGroupingTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestparametergroupingtestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_vendor.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/__init__.py deleted file mode 100644 index 2d6094bc577..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterGroupingTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterGroupingTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_client.py deleted file mode 100644 index c3d1c8c9815..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestParameterGroupingTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterGroupingTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestParameterGroupingTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `azureparametergroupinglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from azureparametergroupinglowlevel.rest import parameter_grouping - >>> request = parameter_grouping.build_post_required_request(path, json=json, custom_header=custom_header, query=query, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestParameterGroupingTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_configuration.py deleted file mode 100644 index 86d1c745c39..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestParameterGroupingTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterGroupingTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestParameterGroupingTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestparametergroupingtestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/parameter_grouping/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/parameter_grouping/__init__.py deleted file mode 100644 index 414f102a44d..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/parameter_grouping/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_post_required_request -from ._request_builders import build_post_optional_request -from ._request_builders import build_post_reserved_words_request -from ._request_builders import build_post_multi_param_groups_request -from ._request_builders import build_post_shared_parameter_group_object_request -from ._request_builders import build_group_with_constant_request - -__all__ = [ - "build_post_required_request", - "build_post_optional_request", - "build_post_reserved_words_request", - "build_post_multi_param_groups_request", - "build_post_shared_parameter_group_object_request", - "build_group_with_constant_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/parameter_grouping/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/parameter_grouping/_request_builders.py deleted file mode 100644 index 839ec8a133a..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/azureparametergroupinglowlevel/rest/parameter_grouping/_request_builders.py +++ /dev/null @@ -1,264 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_post_required_request( - path: str, *, json: int, custom_header: Optional[str] = None, query: int = 30, **kwargs: Any -) -> HttpRequest: - """Post a bunch of required parameters grouped. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param path: Path parameter. Required. - :type path: str - :keyword json: Required. - :paramtype json: int - :keyword custom_header: Default value is None. - :paramtype custom_header: str - :keyword query: Query parameter with default. Default value is 30. - :paramtype query: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/parameterGrouping/postRequired/{path}" - path_format_arguments = { - "path": _SERIALIZER.url("path", path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - if query is not None: - _params["query"] = _SERIALIZER.query("query", query, "int") - - # Construct headers - if custom_header is not None: - _headers["customHeader"] = _SERIALIZER.header("custom_header", custom_header, "str") - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, json=json, **kwargs) - - -def build_post_optional_request(*, custom_header: Optional[str] = None, query: int = 30, **kwargs: Any) -> HttpRequest: - """Post a bunch of optional parameters grouped. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword custom_header: Default value is None. - :paramtype custom_header: str - :keyword query: Query parameter with default. Default value is 30. - :paramtype query: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/parameterGrouping/postOptional" - - # Construct parameters - if query is not None: - _params["query"] = _SERIALIZER.query("query", query, "int") - - # Construct headers - if custom_header is not None: - _headers["customHeader"] = _SERIALIZER.header("custom_header", custom_header, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_post_reserved_words_request( - *, from_parameter: Optional[str] = None, accept_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Post a grouped parameters with reserved words. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword from_parameter: 'from' is a reserved word. Pass in 'bob' to pass. Default value is - None. - :paramtype from_parameter: str - :keyword accept_parameter: 'accept' is a reserved word. Pass in 'yes' to pass. Default value is - None. - :paramtype accept_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/parameterGrouping/postReservedWords" - - # Construct parameters - if from_parameter is not None: - _params["from"] = _SERIALIZER.query("from_parameter", from_parameter, "str") - if accept_parameter is not None: - _params["accept"] = _SERIALIZER.query("accept_parameter", accept_parameter, "str") - - return HttpRequest(method="POST", url=_url, params=_params, **kwargs) - - -def build_post_multi_param_groups_request( - *, - header_one: Optional[str] = None, - query_one: int = 30, - header_two: Optional[str] = None, - query_two: int = 30, - **kwargs: Any -) -> HttpRequest: - """Post parameters from multiple different parameter groups. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword header_one: Default value is None. - :paramtype header_one: str - :keyword query_one: Query parameter with default. Default value is 30. - :paramtype query_one: int - :keyword header_two: Default value is None. - :paramtype header_two: str - :keyword query_two: Query parameter with default. Default value is 30. - :paramtype query_two: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/parameterGrouping/postMultipleParameterGroups" - - # Construct parameters - if query_one is not None: - _params["query-one"] = _SERIALIZER.query("query_one", query_one, "int") - if query_two is not None: - _params["query-two"] = _SERIALIZER.query("query_two", query_two, "int") - - # Construct headers - if header_one is not None: - _headers["header-one"] = _SERIALIZER.header("header_one", header_one, "str") - if header_two is not None: - _headers["header-two"] = _SERIALIZER.header("header_two", header_two, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_post_shared_parameter_group_object_request( - *, header_one: Optional[str] = None, query_one: int = 30, **kwargs: Any -) -> HttpRequest: - """Post parameters with a shared parameter group object. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword header_one: Default value is None. - :paramtype header_one: str - :keyword query_one: Query parameter with default. Default value is 30. - :paramtype query_one: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/parameterGrouping/sharedParameterGroupObject" - - # Construct parameters - if query_one is not None: - _params["query-one"] = _SERIALIZER.query("query_one", query_one, "int") - - # Construct headers - if header_one is not None: - _headers["header-one"] = _SERIALIZER.header("header_one", header_one, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_group_with_constant_request( - *, grouped_constant: str = "foo", grouped_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Parameter group with a constant. Pass in 'foo' for groupedConstant and 'bar' for - groupedParameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword grouped_constant: A grouped parameter that is a constant. Known values are "foo" and - None. Default value is "foo". - :paramtype grouped_constant: str - :keyword grouped_parameter: Optional parameter part of a parameter grouping. Default value is - None. - :paramtype grouped_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/parameterGrouping/groupWithConstant" - - # Construct headers - if grouped_constant is not None: - _headers["groupedConstant"] = _SERIALIZER.header("grouped_constant", grouped_constant, "str") - if grouped_parameter is not None: - _headers["groupedParameter"] = _SERIALIZER.header("grouped_parameter", grouped_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/setup.py deleted file mode 100644 index 4d957fc1486..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureParameterGroupingLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestparametergroupingtestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestParameterGroupingTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/__init__.py deleted file mode 100644 index 90e73b961f9..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestReportServiceForAzure -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestReportServiceForAzure"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_client.py deleted file mode 100644 index 87224f2fe9b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestReportServiceForAzureConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestReportServiceForAzure: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestReportServiceForAzureConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `azurereportlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from azurereportlowlevel.rest import build_get_report_request - >>> request = build_get_report_request(qualifier=qualifier, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestReportServiceForAzure - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_configuration.py deleted file mode 100644 index ca4c15656d6..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestReportServiceForAzureConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestReportServiceForAzure. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestReportServiceForAzureConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestreportserviceforazure/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/__init__.py deleted file mode 100644 index fc184674d48..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestReportServiceForAzure - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestReportServiceForAzure"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_client.py deleted file mode 100644 index b6f14285bd4..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestReportServiceForAzureConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestReportServiceForAzure: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestReportServiceForAzureConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `azurereportlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from azurereportlowlevel.rest import build_get_report_request - >>> request = build_get_report_request(qualifier=qualifier, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestReportServiceForAzure": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_configuration.py deleted file mode 100644 index d5789eafc0d..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestReportServiceForAzureConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestReportServiceForAzure. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestReportServiceForAzureConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestreportserviceforazure/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/rest/__init__.py deleted file mode 100644 index 27743cef8de..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/rest/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_report_request - -__all__ = [ - "build_get_report_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/rest/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/rest/_request_builders.py deleted file mode 100644 index db8e813c2d9..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/azurereportlowlevel/rest/_request_builders.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_report_request(*, qualifier: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Get test coverage report. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword qualifier: If specified, qualifies the generated report further (e.g. '2.7' vs '3.5' - in for Python). The only effect is, that generators that run all tests several times, can - distinguish the generated reports. Default value is None. - :paramtype qualifier: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/report/azure" - - # Construct parameters - if qualifier is not None: - _params["qualifier"] = _SERIALIZER.query("qualifier", qualifier, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/setup.py deleted file mode 100644 index 57a19de97ff..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureReportLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestreportserviceforazure" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestReportServiceForAzure", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/__init__.py deleted file mode 100644 index fbe856f5def..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestAzureSpecialParametersTestClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestAzureSpecialParametersTestClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_client.py deleted file mode 100644 index 2ac41ef4473..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_client.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core.rest import HttpRequest, HttpResponse -from azure.mgmt.core import ARMPipelineClient - -from ._configuration import AutoRestAzureSpecialParametersTestClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials import TokenCredential - - -class AutoRestAzureSpecialParametersTestClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param subscription_id: The subscription id, which appears in the path, always modeled in - credentials. The value is always '1234-5678-9012-3456'. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - :keyword api_version: Api Version. Default value is "2015-07-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - subscription_id: str, - credential: "TokenCredential", - *, - endpoint: str = "http://localhost:3000", - **kwargs: Any - ) -> None: - self._config = AutoRestAzureSpecialParametersTestClientConfiguration( - subscription_id=subscription_id, credential=credential, **kwargs - ) - self._client = ARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `azurespecialpropertieslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from azurespecialpropertieslowlevel.rest import xms_client_request_id - >>> request = xms_client_request_id.build_get_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestAzureSpecialParametersTestClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_configuration.py deleted file mode 100644 index 96593b328d4..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_configuration.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import TokenCredential - - -class AutoRestAzureSpecialParametersTestClientConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestAzureSpecialParametersTestClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param subscription_id: The subscription id, which appears in the path, always modeled in - credentials. The value is always '1234-5678-9012-3456'. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: Api Version. Default value is "2015-07-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, subscription_id: str, credential: "TokenCredential", **kwargs: Any) -> None: - super(AutoRestAzureSpecialParametersTestClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2015-07-01-preview") # type: str - - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.subscription_id = subscription_id - self.credential = credential - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "autorestazurespecialparameterstestclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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.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 - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_vendor.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/__init__.py deleted file mode 100644 index e877a1a6ffb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestAzureSpecialParametersTestClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestAzureSpecialParametersTestClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_client.py deleted file mode 100644 index f60f2649416..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_client.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.mgmt.core import AsyncARMPipelineClient - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestAzureSpecialParametersTestClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials_async import AsyncTokenCredential - - -class AutoRestAzureSpecialParametersTestClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param subscription_id: The subscription id, which appears in the path, always modeled in - credentials. The value is always '1234-5678-9012-3456'. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - :keyword api_version: Api Version. Default value is "2015-07-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - subscription_id: str, - credential: "AsyncTokenCredential", - *, - endpoint: str = "http://localhost:3000", - **kwargs: Any - ) -> None: - self._config = AutoRestAzureSpecialParametersTestClientConfiguration( - subscription_id=subscription_id, credential=credential, **kwargs - ) - self._client = AsyncARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `azurespecialpropertieslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from azurespecialpropertieslowlevel.rest import xms_client_request_id - >>> request = xms_client_request_id.build_get_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestAzureSpecialParametersTestClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_configuration.py deleted file mode 100644 index a6cd3291972..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_configuration.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials_async import AsyncTokenCredential - - -class AutoRestAzureSpecialParametersTestClientConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestAzureSpecialParametersTestClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param subscription_id: The subscription id, which appears in the path, always modeled in - credentials. The value is always '1234-5678-9012-3456'. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: Api Version. Default value is "2015-07-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, subscription_id: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(AutoRestAzureSpecialParametersTestClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2015-07-01-preview") # type: str - - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.subscription_id = subscription_id - self.credential = credential - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "autorestazurespecialparameterstestclient/{}".format(VERSION)) - 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") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_default/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_default/__init__.py deleted file mode 100644 index 65abc045813..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_default/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_method_global_valid_request -from ._request_builders import build_get_method_global_not_provided_valid_request -from ._request_builders import build_get_path_global_valid_request -from ._request_builders import build_get_swagger_global_valid_request - -__all__ = [ - "build_get_method_global_valid_request", - "build_get_method_global_not_provided_valid_request", - "build_get_path_global_valid_request", - "build_get_swagger_global_valid_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_default/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_default/_request_builders.py deleted file mode 100644 index ef9c32371ed..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_default/_request_builders.py +++ /dev/null @@ -1,136 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_method_global_valid_request(**kwargs: Any) -> HttpRequest: - """GET method with api-version modeled in global settings. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/apiVersion/method/string/none/query/global/2015-07-01-preview" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_method_global_not_provided_valid_request(**kwargs: Any) -> HttpRequest: - """GET method with api-version modeled in global settings. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/apiVersion/method/string/none/query/globalNotProvided/2015-07-01-preview" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_path_global_valid_request(**kwargs: Any) -> HttpRequest: - """GET method with api-version modeled in global settings. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/apiVersion/path/string/none/query/global/2015-07-01-preview" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_swagger_global_valid_request(**kwargs: Any) -> HttpRequest: - """GET method with api-version modeled in global settings. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/apiVersion/swagger/string/none/query/global/2015-07-01-preview" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_local/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_local/__init__.py deleted file mode 100644 index 86fa8963847..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_local/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_method_local_valid_request -from ._request_builders import build_get_method_local_null_request -from ._request_builders import build_get_path_local_valid_request -from ._request_builders import build_get_swagger_local_valid_request - -__all__ = [ - "build_get_method_local_valid_request", - "build_get_method_local_null_request", - "build_get_path_local_valid_request", - "build_get_swagger_local_valid_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_local/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_local/_request_builders.py deleted file mode 100644 index 2bfde64615b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/api_version_local/_request_builders.py +++ /dev/null @@ -1,149 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_method_local_valid_request(**kwargs: Any) -> HttpRequest: - """Get method with api-version modeled in the method. pass in api-version = '2.0' to succeed. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword api_version: This should appear as a method parameter, use value '2.0'. Default value - is "2.0". Note that overriding this default value may result in unsupported behavior. - :paramtype api_version: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2.0")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/apiVersion/method/string/none/query/local/2.0" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_method_local_null_request(*, api_version: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Get method with api-version modeled in the method. pass in api-version = null to succeed. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword api_version: This should appear as a method parameter, use value null, this should - result in no serialized parameter. Default value is None. - :paramtype api_version: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/apiVersion/method/string/none/query/local/null" - - # Construct parameters - if api_version is not None: - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_path_local_valid_request(**kwargs: Any) -> HttpRequest: - """Get method with api-version modeled in the method. pass in api-version = '2.0' to succeed. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword api_version: This should appear as a method parameter, use value '2.0'. Default value - is "2.0". Note that overriding this default value may result in unsupported behavior. - :paramtype api_version: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2.0")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/apiVersion/path/string/none/query/local/2.0" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_swagger_local_valid_request(**kwargs: Any) -> HttpRequest: - """Get method with api-version modeled in the method. pass in api-version = '2.0' to succeed. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword api_version: The api version, which appears in the query, the value is always '2.0'. - Default value is "2.0". Note that overriding this default value may result in unsupported - behavior. - :paramtype api_version: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2.0")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/apiVersion/swagger/string/none/query/local/2.0" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/header/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/header/__init__.py deleted file mode 100644 index 656d7c21179..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/header/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_custom_named_request_id_request -from ._request_builders import build_custom_named_request_id_param_grouping_request -from ._request_builders import build_custom_named_request_id_head_request - -__all__ = [ - "build_custom_named_request_id_request", - "build_custom_named_request_id_param_grouping_request", - "build_custom_named_request_id_head_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/header/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/header/_request_builders.py deleted file mode 100644 index 35fe7f84997..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/header/_request_builders.py +++ /dev/null @@ -1,101 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_custom_named_request_id_request(*, foo_client_request_id: str, **kwargs: Any) -> HttpRequest: - """Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword foo_client_request_id: The fooRequestId. Required. - :paramtype foo_client_request_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/customNamedRequestId" - - # Construct headers - _headers["foo-client-request-id"] = _SERIALIZER.header("foo_client_request_id", foo_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_custom_named_request_id_param_grouping_request(*, foo_client_request_id: str, **kwargs: Any) -> HttpRequest: - """Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request, - via a parameter group. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword foo_client_request_id: The fooRequestId. Required. - :paramtype foo_client_request_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/customNamedRequestIdParamGrouping" - - # Construct headers - _headers["foo-client-request-id"] = _SERIALIZER.header("foo_client_request_id", foo_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_custom_named_request_id_head_request(*, foo_client_request_id: str, **kwargs: Any) -> HttpRequest: - """Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword foo_client_request_id: The fooRequestId. Required. - :paramtype foo_client_request_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/customNamedRequestIdHead" - - # Construct headers - _headers["foo-client-request-id"] = _SERIALIZER.header("foo_client_request_id", foo_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/odata/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/odata/__init__.py deleted file mode 100644 index e8fe5dde319..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/odata/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_with_filter_request - -__all__ = [ - "build_get_with_filter_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/odata/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/odata/_request_builders.py deleted file mode 100644 index 9de2fc82b22..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/odata/_request_builders.py +++ /dev/null @@ -1,59 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_with_filter_request( - *, filter: Optional[str] = None, top: Optional[int] = None, orderby: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Specify filter parameter with value '$filter=id gt 5 and name eq 'foo'&$orderby=id&$top=10'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword filter: The filter parameter with value '$filter=id gt 5 and name eq 'foo''. Default - value is None. - :paramtype filter: str - :keyword top: The top parameter with value 10. Default value is None. - :paramtype top: int - :keyword orderby: The orderby parameter with value id. Default value is None. - :paramtype orderby: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/odata/filter" - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - if top is not None: - _params["$top"] = _SERIALIZER.query("top", top, "int") - if orderby is not None: - _params["$orderby"] = _SERIALIZER.query("orderby", orderby, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/skip_url_encoding/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/skip_url_encoding/__init__.py deleted file mode 100644 index e1f7ba1be74..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/skip_url_encoding/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_method_path_valid_request -from ._request_builders import build_get_path_valid_request -from ._request_builders import build_get_swagger_path_valid_request -from ._request_builders import build_get_method_query_valid_request -from ._request_builders import build_get_method_query_null_request -from ._request_builders import build_get_path_query_valid_request -from ._request_builders import build_get_swagger_query_valid_request - -__all__ = [ - "build_get_method_path_valid_request", - "build_get_path_valid_request", - "build_get_swagger_path_valid_request", - "build_get_method_query_valid_request", - "build_get_method_query_null_request", - "build_get_path_query_valid_request", - "build_get_swagger_query_valid_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/skip_url_encoding/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/skip_url_encoding/_request_builders.py deleted file mode 100644 index 7eded9a2315..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/skip_url_encoding/_request_builders.py +++ /dev/null @@ -1,244 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_method_path_valid_request(unencoded_path_param: str, **kwargs: Any) -> HttpRequest: - """Get method with unencoded path parameter with value 'path1/path2/path3'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param unencoded_path_param: Unencoded path parameter with value 'path1/path2/path3'. Required. - :type unencoded_path_param: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/skipUrlEncoding/method/path/valid/{unencodedPathParam}" - path_format_arguments = { - "unencodedPathParam": _SERIALIZER.url("unencoded_path_param", unencoded_path_param, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_path_valid_request(unencoded_path_param: str, **kwargs: Any) -> HttpRequest: - """Get method with unencoded path parameter with value 'path1/path2/path3'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param unencoded_path_param: Unencoded path parameter with value 'path1/path2/path3'. Required. - :type unencoded_path_param: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/skipUrlEncoding/path/path/valid/{unencodedPathParam}" - path_format_arguments = { - "unencodedPathParam": _SERIALIZER.url("unencoded_path_param", unencoded_path_param, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_swagger_path_valid_request(**kwargs: Any) -> HttpRequest: - """Get method with unencoded path parameter with value 'path1/path2/path3'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword unencoded_path_param: An unencoded path parameter with value 'path1/path2/path3'. - Default value is "path1/path2/path3". Note that overriding this default value may result in - unsupported behavior. - :paramtype unencoded_path_param: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - unencoded_path_param = kwargs.pop("unencoded_path_param", "path1/path2/path3") # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/skipUrlEncoding/swagger/path/valid/{unencodedPathParam}" - path_format_arguments = { - "unencodedPathParam": _SERIALIZER.url("unencoded_path_param", unencoded_path_param, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_method_query_valid_request(*, q1: str, **kwargs: Any) -> HttpRequest: - """Get method with unencoded query parameter with value 'value1&q2=value2&q3=value3'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword q1: Unencoded query parameter with value 'value1&q2=value2&q3=value3'. Required. - :paramtype q1: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/skipUrlEncoding/method/query/valid" - - # Construct parameters - _params["q1"] = _SERIALIZER.query("q1", q1, "str", skip_quote=True) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_method_query_null_request(*, q1: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Get method with unencoded query parameter with value null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword q1: Unencoded query parameter with value null. Default value is None. - :paramtype q1: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/skipUrlEncoding/method/query/null" - - # Construct parameters - if q1 is not None: - _params["q1"] = _SERIALIZER.query("q1", q1, "str", skip_quote=True) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_path_query_valid_request(*, q1: str, **kwargs: Any) -> HttpRequest: - """Get method with unencoded query parameter with value 'value1&q2=value2&q3=value3'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword q1: Unencoded query parameter with value 'value1&q2=value2&q3=value3'. Required. - :paramtype q1: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/skipUrlEncoding/path/query/valid" - - # Construct parameters - _params["q1"] = _SERIALIZER.query("q1", q1, "str", skip_quote=True) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_swagger_query_valid_request(**kwargs: Any) -> HttpRequest: - """Get method with unencoded query parameter with value 'value1&q2=value2&q3=value3'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword q1: An unencoded query parameter with value 'value1&q2=value2&q3=value3'. Default - value is "value1&q2=value2&q3=value3". Note that overriding this default value may result in - unsupported behavior. - :paramtype q1: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - q1 = kwargs.pop("q1", _params.pop("q1", "value1&q2=value2&q3=value3")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/skipUrlEncoding/swagger/query/valid" - - # Construct parameters - _params["q1"] = _SERIALIZER.query("q1", q1, "str", skip_quote=True) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_credentials/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_credentials/__init__.py deleted file mode 100644 index 5b837125d8d..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_credentials/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_post_method_global_valid_request -from ._request_builders import build_post_method_global_null_request -from ._request_builders import build_post_method_global_not_provided_valid_request -from ._request_builders import build_post_path_global_valid_request -from ._request_builders import build_post_swagger_global_valid_request - -__all__ = [ - "build_post_method_global_valid_request", - "build_post_method_global_null_request", - "build_post_method_global_not_provided_valid_request", - "build_post_path_global_valid_request", - "build_post_swagger_global_valid_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_credentials/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_credentials/_request_builders.py deleted file mode 100644 index 096fe065d4b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_credentials/_request_builders.py +++ /dev/null @@ -1,194 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_post_method_global_valid_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to - '1234-5678-9012-3456' to succeed. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: The subscription id, which appears in the path, always modeled in - credentials. The value is always '1234-5678-9012-3456'. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/subscriptionId/method/string/none/path/global/1234-5678-9012-3456/{subscriptionId}" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_method_global_null_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to - null, and client-side validation should prevent you from making this call. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: The subscription id, which appears in the path, always modeled in - credentials. The value is always '1234-5678-9012-3456'. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/subscriptionId/method/string/none/path/global/null/{subscriptionId}" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_method_global_not_provided_valid_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to - '1234-5678-9012-3456' to succeed. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: The subscription id, which appears in the path, always modeled in - credentials. The value is always '1234-5678-9012-3456'. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-07-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = ( - "/azurespecials/subscriptionId/method/string/none/path/globalNotProvided/1234-5678-9012-3456/{subscriptionId}" - ) - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_post_path_global_valid_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to - '1234-5678-9012-3456' to succeed. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: The subscription id, which appears in the path, always modeled in - credentials. The value is always '1234-5678-9012-3456'. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/subscriptionId/path/string/none/path/global/1234-5678-9012-3456/{subscriptionId}" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_swagger_global_valid_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """POST method with subscriptionId modeled in credentials. Set the credential subscriptionId to - '1234-5678-9012-3456' to succeed. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: The subscription id, which appears in the path, always modeled in - credentials. The value is always '1234-5678-9012-3456'. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/subscriptionId/swagger/string/none/path/global/1234-5678-9012-3456/{subscriptionId}" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_method/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_method/__init__.py deleted file mode 100644 index 5ab9b3bbdc1..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_method/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_post_method_local_valid_request -from ._request_builders import build_post_method_local_null_request -from ._request_builders import build_post_path_local_valid_request -from ._request_builders import build_post_swagger_local_valid_request - -__all__ = [ - "build_post_method_local_valid_request", - "build_post_method_local_null_request", - "build_post_path_local_valid_request", - "build_post_swagger_local_valid_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_method/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_method/_request_builders.py deleted file mode 100644 index b74962412b8..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/subscription_in_method/_request_builders.py +++ /dev/null @@ -1,153 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_post_method_local_valid_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """POST method with subscriptionId modeled in the method. pass in subscription id = - '1234-5678-9012-3456' to succeed. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: This should appear as a method parameter, use value - '1234-5678-9012-3456'. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/subscriptionId/method/string/none/path/local/1234-5678-9012-3456/{subscriptionId}" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_method_local_null_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """POST method with subscriptionId modeled in the method. pass in subscription id = null, - client-side validation should prevent you from making this call. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: This should appear as a method parameter, use value null, client-side - validation should prvenet the call. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/subscriptionId/method/string/none/path/local/null/{subscriptionId}" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_path_local_valid_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """POST method with subscriptionId modeled in the method. pass in subscription id = - '1234-5678-9012-3456' to succeed. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: Should appear as a method parameter -use value '1234-5678-9012-3456'. - Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/subscriptionId/path/string/none/path/local/1234-5678-9012-3456/{subscriptionId}" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_swagger_local_valid_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """POST method with subscriptionId modeled in the method. pass in subscription id = - '1234-5678-9012-3456' to succeed. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: The subscriptionId, which appears in the path, the value is always - '1234-5678-9012-3456'. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/subscriptionId/swagger/string/none/path/local/1234-5678-9012-3456/{subscriptionId}" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/xms_client_request_id/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/xms_client_request_id/__init__.py deleted file mode 100644 index 8ba2b17ba2d..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/xms_client_request_id/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_request -from ._request_builders import build_param_get_request - -__all__ = [ - "build_get_request", - "build_param_get_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/xms_client_request_id/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/xms_client_request_id/_request_builders.py deleted file mode 100644 index bd34cfe853a..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/azurespecialpropertieslowlevel/rest/xms_client_request_id/_request_builders.py +++ /dev/null @@ -1,65 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_request(**kwargs: Any) -> HttpRequest: - """Get method that overwrites x-ms-client-request header with value - 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/azurespecials/overwrite/x-ms-client-request-id/method/" - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_param_get_request(*, x_ms_client_request_id: str, **kwargs: Any) -> HttpRequest: - """Get method that overwrites x-ms-client-request header with value - 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword x_ms_client_request_id: This should appear as a method parameter, use value - '9C4D50EE-2D56-4CD3-8152-34347DC9F2B0'. Required. - :paramtype x_ms_client_request_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/azurespecials/overwrite/x-ms-client-request-id/via-param/method/" - - # Construct headers - _headers["x-ms-client-request-id"] = _SERIALIZER.header("x_ms_client_request_id", x_ms_client_request_id, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/setup.py deleted file mode 100644 index 5091819ec4a..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/AzureSpecialsLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestazurespecialparameterstestclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestAzureSpecialParametersTestClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-mgmt-core<2.0.0,>=1.3.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/__init__.py deleted file mode 100644 index 142d64ad945..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterizedHostTestClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterizedHostTestClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_client.py deleted file mode 100644 index 6c01f101c9e..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_client.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestParameterizedHostTestClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterizedHostTestClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - _endpoint = "http://{accountName}{host}" - self._config = AutoRestParameterizedHostTestClientConfiguration(host=host, **kwargs) - self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `custombaseurllowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from custombaseurllowlevel.rest import paths - >>> request = paths.build_get_empty_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestParameterizedHostTestClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_configuration.py deleted file mode 100644 index 8b25be0e943..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_configuration.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestParameterizedHostTestClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterizedHostTestClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - super(AutoRestParameterizedHostTestClientConfiguration, self).__init__(**kwargs) - if host is None: - raise ValueError("Parameter 'host' must not be None.") - - self.host = host - kwargs.setdefault("sdk_moniker", "autorestparameterizedhosttestclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/__init__.py deleted file mode 100644 index 5bfa1ff304b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterizedHostTestClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterizedHostTestClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_client.py deleted file mode 100644 index 790c3d1fe85..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_client.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestParameterizedHostTestClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterizedHostTestClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - _endpoint = "http://{accountName}{host}" - self._config = AutoRestParameterizedHostTestClientConfiguration(host=host, **kwargs) - self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `custombaseurllowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from custombaseurllowlevel.rest import paths - >>> request = paths.build_get_empty_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestParameterizedHostTestClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_configuration.py deleted file mode 100644 index e2d2a50345b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_configuration.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestParameterizedHostTestClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterizedHostTestClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - super(AutoRestParameterizedHostTestClientConfiguration, self).__init__(**kwargs) - if host is None: - raise ValueError("Parameter 'host' must not be None.") - - self.host = host - kwargs.setdefault("sdk_moniker", "autorestparameterizedhosttestclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/__init__.py deleted file mode 100644 index b03437179b1..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_empty_request - -__all__ = [ - "build_get_empty_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/_request_builders.py deleted file mode 100644 index feca717c807..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/_request_builders.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_empty_request(**kwargs: Any) -> HttpRequest: - """Get a 200 to test a valid base uri. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/customuri" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/setup.py deleted file mode 100644 index e4fd12e45ab..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestparameterizedhosttestclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestParameterizedHostTestClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/__init__.py deleted file mode 100644 index 03790d64c99..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterizedHostTestPagingClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterizedHostTestPagingClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_client.py deleted file mode 100644 index 468d99b3f00..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_client.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestParameterizedHostTestPagingClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterizedHostTestPagingClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - _endpoint = "http://{accountName}{host}" - self._config = AutoRestParameterizedHostTestPagingClientConfiguration(host=host, **kwargs) - self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `custombaseurlpaginglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from custombaseurlpaginglowlevel.rest import paging - >>> request = paging.build_get_pages_partial_url_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestParameterizedHostTestPagingClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_configuration.py deleted file mode 100644 index 1cb08d80f7e..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_configuration.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestParameterizedHostTestPagingClientConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterizedHostTestPagingClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - super(AutoRestParameterizedHostTestPagingClientConfiguration, self).__init__(**kwargs) - if host is None: - raise ValueError("Parameter 'host' must not be None.") - - self.host = host - kwargs.setdefault("sdk_moniker", "autorestparameterizedhosttestpagingclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_vendor.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/__init__.py deleted file mode 100644 index f99ebdf9f8e..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterizedHostTestPagingClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterizedHostTestPagingClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_client.py deleted file mode 100644 index ca7f7c37c4c..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_client.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestParameterizedHostTestPagingClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterizedHostTestPagingClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - _endpoint = "http://{accountName}{host}" - self._config = AutoRestParameterizedHostTestPagingClientConfiguration(host=host, **kwargs) - self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `custombaseurlpaginglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from custombaseurlpaginglowlevel.rest import paging - >>> request = paging.build_get_pages_partial_url_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestParameterizedHostTestPagingClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_configuration.py deleted file mode 100644 index 6ee0b236f44..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_configuration.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestParameterizedHostTestPagingClientConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterizedHostTestPagingClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - super(AutoRestParameterizedHostTestPagingClientConfiguration, self).__init__(**kwargs) - if host is None: - raise ValueError("Parameter 'host' must not be None.") - - self.host = host - kwargs.setdefault("sdk_moniker", "autorestparameterizedhosttestpagingclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/paging/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/paging/__init__.py deleted file mode 100644 index fcad56b77b7..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/paging/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_pages_partial_url_request -from ._request_builders import build_get_pages_partial_url_operation_request -from ._request_builders import build_get_pages_partial_url_operation_next_request - -__all__ = [ - "build_get_pages_partial_url_request", - "build_get_pages_partial_url_operation_request", - "build_get_pages_partial_url_operation_next_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/paging/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/paging/_request_builders.py deleted file mode 100644 index 9615b2833d0..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/custombaseurlpaginglowlevel/rest/paging/_request_builders.py +++ /dev/null @@ -1,100 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_pages_partial_url_request(**kwargs: Any) -> HttpRequest: - """A paging operation that combines custom url, paging and partial URL and expect to concat after - host. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/customurl/partialnextlink" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_pages_partial_url_operation_request(**kwargs: Any) -> HttpRequest: - """A paging operation that combines custom url, paging and partial URL with next operation. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/customurl/partialnextlinkop" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_pages_partial_url_operation_next_request(next_link: str, **kwargs: Any) -> HttpRequest: - """A paging operation that combines custom url, paging and partial URL - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param next_link: Next link for the list operation. Required. - :type next_link: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/customurl/{nextLink}" - path_format_arguments = { - "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/setup.py deleted file mode 100644 index 6da300de4bd..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/CustomUrlPagingLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestparameterizedhosttestpagingclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestParameterizedHostTestPagingClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/__init__.py deleted file mode 100644 index 9ebac46a75d..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestHeadExceptionTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestHeadExceptionTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_client.py deleted file mode 100644 index 1e8bbe2854e..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_client.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core.rest import HttpRequest, HttpResponse -from azure.mgmt.core import ARMPipelineClient - -from ._configuration import AutoRestHeadExceptionTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials import TokenCredential - - -class AutoRestHeadExceptionTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, credential: "TokenCredential", *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - self._config = AutoRestHeadExceptionTestServiceConfiguration(credential=credential, **kwargs) - self._client = ARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `headexceptionslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from headexceptionslowlevel.rest import head_exception - >>> request = head_exception.build_head200_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestHeadExceptionTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_configuration.py deleted file mode 100644 index 02dca35a5d1..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_configuration.py +++ /dev/null @@ -1,58 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import TokenCredential - - -class AutoRestHeadExceptionTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestHeadExceptionTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - """ - - def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(AutoRestHeadExceptionTestServiceConfiguration, self).__init__(**kwargs) - 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", "autorestheadexceptiontestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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.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 - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/__init__.py deleted file mode 100644 index 31a5dc27d54..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestHeadExceptionTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestHeadExceptionTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_client.py deleted file mode 100644 index 448d2047cbb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_client.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.mgmt.core import AsyncARMPipelineClient - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestHeadExceptionTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials_async import AsyncTokenCredential - - -class AutoRestHeadExceptionTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, credential: "AsyncTokenCredential", *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - self._config = AutoRestHeadExceptionTestServiceConfiguration(credential=credential, **kwargs) - self._client = AsyncARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `headexceptionslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from headexceptionslowlevel.rest import head_exception - >>> request = head_exception.build_head200_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestHeadExceptionTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_configuration.py deleted file mode 100644 index 9b845e4973e..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_configuration.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials_async import AsyncTokenCredential - - -class AutoRestHeadExceptionTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestHeadExceptionTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - """ - - def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(AutoRestHeadExceptionTestServiceConfiguration, self).__init__(**kwargs) - 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", "autorestheadexceptiontestservice/{}".format(VERSION)) - 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") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/head_exception/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/head_exception/__init__.py deleted file mode 100644 index a311ff2bf79..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/head_exception/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_head200_request -from ._request_builders import build_head204_request -from ._request_builders import build_head404_request - -__all__ = [ - "build_head200_request", - "build_head204_request", - "build_head404_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/head_exception/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/head_exception/_request_builders.py deleted file mode 100644 index efe990563d3..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/headexceptionslowlevel/rest/head_exception/_request_builders.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_head200_request(**kwargs: Any) -> HttpRequest: - """Return 200 status code if successful. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/success/200" - - return HttpRequest(method="HEAD", url=_url, **kwargs) - - -def build_head204_request(**kwargs: Any) -> HttpRequest: - """Return 204 status code if successful. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/success/204" - - return HttpRequest(method="HEAD", url=_url, **kwargs) - - -def build_head404_request(**kwargs: Any) -> HttpRequest: - """Return 404 status code if successful. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/success/404" - - return HttpRequest(method="HEAD", url=_url, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/setup.py deleted file mode 100644 index e63f2817d84..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadExceptionsLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestheadexceptiontestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestHeadExceptionTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-mgmt-core<2.0.0,>=1.3.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/__init__.py deleted file mode 100644 index 4e88b33e40b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestHeadTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestHeadTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_client.py deleted file mode 100644 index 03be12b794b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_client.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core.rest import HttpRequest, HttpResponse -from azure.mgmt.core import ARMPipelineClient - -from ._configuration import AutoRestHeadTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials import TokenCredential - - -class AutoRestHeadTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, credential: "TokenCredential", *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - self._config = AutoRestHeadTestServiceConfiguration(credential=credential, **kwargs) - self._client = ARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `headlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from headlowlevel.rest import http_success - >>> request = http_success.build_head200_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestHeadTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_configuration.py deleted file mode 100644 index 50d08045598..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_configuration.py +++ /dev/null @@ -1,58 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import TokenCredential - - -class AutoRestHeadTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestHeadTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - """ - - def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(AutoRestHeadTestServiceConfiguration, self).__init__(**kwargs) - 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", "autorestheadtestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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.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 - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/__init__.py deleted file mode 100644 index d70ad195554..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestHeadTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestHeadTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_client.py deleted file mode 100644 index b36bc1baa7b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_client.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.mgmt.core import AsyncARMPipelineClient - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestHeadTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials_async import AsyncTokenCredential - - -class AutoRestHeadTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, credential: "AsyncTokenCredential", *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - self._config = AutoRestHeadTestServiceConfiguration(credential=credential, **kwargs) - self._client = AsyncARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `headlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from headlowlevel.rest import http_success - >>> request = http_success.build_head200_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestHeadTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_configuration.py deleted file mode 100644 index 9bd103e1821..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_configuration.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials_async import AsyncTokenCredential - - -class AutoRestHeadTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestHeadTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - """ - - def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(AutoRestHeadTestServiceConfiguration, self).__init__(**kwargs) - 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", "autorestheadtestservice/{}".format(VERSION)) - 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") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/http_success/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/http_success/__init__.py deleted file mode 100644 index a311ff2bf79..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/http_success/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_head200_request -from ._request_builders import build_head204_request -from ._request_builders import build_head404_request - -__all__ = [ - "build_head200_request", - "build_head204_request", - "build_head404_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/http_success/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/http_success/_request_builders.py deleted file mode 100644 index efe990563d3..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/headlowlevel/rest/http_success/_request_builders.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_head200_request(**kwargs: Any) -> HttpRequest: - """Return 200 status code if successful. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/success/200" - - return HttpRequest(method="HEAD", url=_url, **kwargs) - - -def build_head204_request(**kwargs: Any) -> HttpRequest: - """Return 204 status code if successful. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/success/204" - - return HttpRequest(method="HEAD", url=_url, **kwargs) - - -def build_head404_request(**kwargs: Any) -> HttpRequest: - """Return 404 status code if successful. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/success/404" - - return HttpRequest(method="HEAD", url=_url, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/setup.py deleted file mode 100644 index a86e39d4fe3..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/HeadLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestheadtestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestHeadTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-mgmt-core<2.0.0,>=1.3.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/__init__.py deleted file mode 100644 index 4cd4c3b406c..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestLongRunningOperationTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestLongRunningOperationTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_client.py deleted file mode 100644 index c2736989588..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_client.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core.rest import HttpRequest, HttpResponse -from azure.mgmt.core import ARMPipelineClient - -from ._configuration import AutoRestLongRunningOperationTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials import TokenCredential - - -class AutoRestLongRunningOperationTestService: # pylint: disable=client-accepts-api-version-keyword - """Long-running Operation for AutoRest. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, credential: "TokenCredential", *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - self._config = AutoRestLongRunningOperationTestServiceConfiguration(credential=credential, **kwargs) - self._client = ARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `lrolowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from lrolowlevel.rest import lros - >>> request = lros.build_put200_succeeded_request(content_type=content_type, json=json, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestLongRunningOperationTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_configuration.py deleted file mode 100644 index d09e45e4990..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_configuration.py +++ /dev/null @@ -1,60 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import TokenCredential - - -class AutoRestLongRunningOperationTestServiceConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestLongRunningOperationTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - """ - - def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(AutoRestLongRunningOperationTestServiceConfiguration, self).__init__(**kwargs) - 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", "autorestlongrunningoperationtestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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.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 - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/__init__.py deleted file mode 100644 index 99ebbc1b6e7..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestLongRunningOperationTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestLongRunningOperationTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_client.py deleted file mode 100644 index e4e9e315da9..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_client.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.mgmt.core import AsyncARMPipelineClient - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestLongRunningOperationTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials_async import AsyncTokenCredential - - -class AutoRestLongRunningOperationTestService: # pylint: disable=client-accepts-api-version-keyword - """Long-running Operation for AutoRest. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, credential: "AsyncTokenCredential", *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - self._config = AutoRestLongRunningOperationTestServiceConfiguration(credential=credential, **kwargs) - self._client = AsyncARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `lrolowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from lrolowlevel.rest import lros - >>> request = lros.build_put200_succeeded_request(content_type=content_type, json=json, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestLongRunningOperationTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_configuration.py deleted file mode 100644 index 94e6bc2fff9..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_configuration.py +++ /dev/null @@ -1,57 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials_async import AsyncTokenCredential - - -class AutoRestLongRunningOperationTestServiceConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestLongRunningOperationTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - """ - - def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(AutoRestLongRunningOperationTestServiceConfiguration, self).__init__(**kwargs) - 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", "autorestlongrunningoperationtestservice/{}".format(VERSION)) - 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") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lr_os_custom_header/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lr_os_custom_header/__init__.py deleted file mode 100644 index af267aa118e..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lr_os_custom_header/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_put_async_retry_succeeded_request -from ._request_builders import build_put201_creating_succeeded200_request -from ._request_builders import build_post202_retry200_request -from ._request_builders import build_post_async_retry_succeeded_request - -__all__ = [ - "build_put_async_retry_succeeded_request", - "build_put201_creating_succeeded200_request", - "build_post202_retry200_request", - "build_post_async_retry_succeeded_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lr_os_custom_header/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lr_os_custom_header/_request_builders.py deleted file mode 100644 index 287b51950a9..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lr_os_custom_header/_request_builders.py +++ /dev/null @@ -1,436 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -@overload -def build_put_async_retry_succeeded_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running put request, service returns a 200 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_retry_succeeded_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running put request, service returns a 200 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_retry_succeeded_request(**kwargs: Any) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running put request, service returns a 200 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/customheader/putasync/retry/succeeded" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put201_creating_succeeded200_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running put request, service returns a 201 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll - returns a ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put201_creating_succeeded200_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running put request, service returns a 201 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll - returns a ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put201_creating_succeeded200_request(**kwargs: Any) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running put request, service returns a 201 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll - returns a ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/customheader/put/201/creating/succeeded/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post202_retry200_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running post request, service returns a 202 to the initial request, with - 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post202_retry200_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running post request, service returns a 202 to the initial request, with - 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post202_retry200_request(**kwargs: Any) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running post request, service returns a 202 to the initial request, with - 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/customheader/post/202/retry/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_async_retry_succeeded_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running post request, service returns a 202 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post_async_retry_succeeded_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running post request, service returns a 202 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_async_retry_succeeded_request(**kwargs: Any) -> HttpRequest: - """x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 is required message header for - all requests. Long running post request, service returns a 202 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/customheader/postasync/retry/succeeded" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lro_retrys/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lro_retrys/__init__.py deleted file mode 100644 index 96da443d477..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lro_retrys/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_put201_creating_succeeded200_request -from ._request_builders import build_put_async_relative_retry_succeeded_request -from ._request_builders import build_delete_provisioning202_accepted200_succeeded_request -from ._request_builders import build_delete202_retry200_request -from ._request_builders import build_delete_async_relative_retry_succeeded_request -from ._request_builders import build_post202_retry200_request -from ._request_builders import build_post_async_relative_retry_succeeded_request - -__all__ = [ - "build_put201_creating_succeeded200_request", - "build_put_async_relative_retry_succeeded_request", - "build_delete_provisioning202_accepted200_succeeded_request", - "build_delete202_retry200_request", - "build_delete_async_relative_retry_succeeded_request", - "build_post202_retry200_request", - "build_post_async_relative_retry_succeeded_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lro_retrys/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lro_retrys/_request_builders.py deleted file mode 100644 index 18fbdd61615..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lro_retrys/_request_builders.py +++ /dev/null @@ -1,503 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -@overload -def build_put201_creating_succeeded200_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 500, then a 201 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll - returns a ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put201_creating_succeeded200_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 500, then a 201 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll - returns a ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put201_creating_succeeded200_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 500, then a 201 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Polls return this value until the last poll - returns a ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/retryerror/put/201/creating/succeeded/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_relative_retry_succeeded_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 500, then a 200 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_relative_retry_succeeded_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 500, then a 200 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_relative_retry_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 500, then a 200 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/retryerror/putasync/retry/succeeded" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_delete_provisioning202_accepted200_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 500, then a 202 to the initial request, with an - entity that contains ProvisioningState=’Accepted’. Polls return this value until the last poll - returns a ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/retryerror/delete/provisioning/202/accepted/200/succeeded" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete202_retry200_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 500, then a 202 to the initial request. Polls - return this value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/retryerror/delete/202/retry/200" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_async_relative_retry_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 500, then a 202 to the initial request. Poll the - endpoint indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/retryerror/deleteasync/retry/succeeded" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post202_retry200_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 500, then a 202 to the initial request, with - 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post202_retry200_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 500, then a 202 to the initial request, with - 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post202_retry200_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 500, then a 202 to the initial request, with - 'Location' and 'Retry-After' headers, Polls return a 200 with a response body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/retryerror/post/202/retry/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_async_relative_retry_succeeded_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 500, then a 202 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post_async_relative_retry_succeeded_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 500, then a 202 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_async_relative_retry_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 500, then a 202 to the initial request, with an - entity that contains ProvisioningState=’Creating’. Poll the endpoint indicated in the - Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/retryerror/postasync/retry/succeeded" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lros/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lros/__init__.py deleted file mode 100644 index d9f9b8a40c8..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lros/__init__.py +++ /dev/null @@ -1,99 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_put200_succeeded_request -from ._request_builders import build_patch200_succeeded_ignore_headers_request -from ._request_builders import build_patch201_retry_with_async_header_request -from ._request_builders import build_patch202_retry_with_async_and_location_header_request -from ._request_builders import build_put201_succeeded_request -from ._request_builders import build_post202_list_request -from ._request_builders import build_put200_succeeded_no_state_request -from ._request_builders import build_put202_retry200_request -from ._request_builders import build_put201_creating_succeeded200_request -from ._request_builders import build_put200_updating_succeeded204_request -from ._request_builders import build_put201_creating_failed200_request -from ._request_builders import build_put200_acceptedcanceled200_request -from ._request_builders import build_put_no_header_in_retry_request -from ._request_builders import build_put_async_retry_succeeded_request -from ._request_builders import build_put_async_no_retry_succeeded_request -from ._request_builders import build_put_async_retry_failed_request -from ._request_builders import build_put_async_no_retrycanceled_request -from ._request_builders import build_put_async_no_header_in_retry_request -from ._request_builders import build_put_non_resource_request -from ._request_builders import build_put_async_non_resource_request -from ._request_builders import build_put_sub_resource_request -from ._request_builders import build_put_async_sub_resource_request -from ._request_builders import build_delete_provisioning202_accepted200_succeeded_request -from ._request_builders import build_delete_provisioning202_deleting_failed200_request -from ._request_builders import build_delete_provisioning202_deletingcanceled200_request -from ._request_builders import build_delete204_succeeded_request -from ._request_builders import build_delete202_retry200_request -from ._request_builders import build_delete202_no_retry204_request -from ._request_builders import build_delete_no_header_in_retry_request -from ._request_builders import build_delete_async_no_header_in_retry_request -from ._request_builders import build_delete_async_retry_succeeded_request -from ._request_builders import build_delete_async_no_retry_succeeded_request -from ._request_builders import build_delete_async_retry_failed_request -from ._request_builders import build_delete_async_retrycanceled_request -from ._request_builders import build_post200_with_payload_request -from ._request_builders import build_post202_retry200_request -from ._request_builders import build_post202_no_retry204_request -from ._request_builders import build_post_double_headers_final_location_get_request -from ._request_builders import build_post_double_headers_final_azure_header_get_request -from ._request_builders import build_post_double_headers_final_azure_header_get_default_request -from ._request_builders import build_post_async_retry_succeeded_request -from ._request_builders import build_post_async_no_retry_succeeded_request -from ._request_builders import build_post_async_retry_failed_request -from ._request_builders import build_post_async_retrycanceled_request - -__all__ = [ - "build_put200_succeeded_request", - "build_patch200_succeeded_ignore_headers_request", - "build_patch201_retry_with_async_header_request", - "build_patch202_retry_with_async_and_location_header_request", - "build_put201_succeeded_request", - "build_post202_list_request", - "build_put200_succeeded_no_state_request", - "build_put202_retry200_request", - "build_put201_creating_succeeded200_request", - "build_put200_updating_succeeded204_request", - "build_put201_creating_failed200_request", - "build_put200_acceptedcanceled200_request", - "build_put_no_header_in_retry_request", - "build_put_async_retry_succeeded_request", - "build_put_async_no_retry_succeeded_request", - "build_put_async_retry_failed_request", - "build_put_async_no_retrycanceled_request", - "build_put_async_no_header_in_retry_request", - "build_put_non_resource_request", - "build_put_async_non_resource_request", - "build_put_sub_resource_request", - "build_put_async_sub_resource_request", - "build_delete_provisioning202_accepted200_succeeded_request", - "build_delete_provisioning202_deleting_failed200_request", - "build_delete_provisioning202_deletingcanceled200_request", - "build_delete204_succeeded_request", - "build_delete202_retry200_request", - "build_delete202_no_retry204_request", - "build_delete_no_header_in_retry_request", - "build_delete_async_no_header_in_retry_request", - "build_delete_async_retry_succeeded_request", - "build_delete_async_no_retry_succeeded_request", - "build_delete_async_retry_failed_request", - "build_delete_async_retrycanceled_request", - "build_post200_with_payload_request", - "build_post202_retry200_request", - "build_post202_no_retry204_request", - "build_post_double_headers_final_location_get_request", - "build_post_double_headers_final_azure_header_get_request", - "build_post_double_headers_final_azure_header_get_default_request", - "build_post_async_retry_succeeded_request", - "build_post_async_no_retry_succeeded_request", - "build_post_async_retry_failed_request", - "build_post_async_retrycanceled_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lros/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lros/_request_builders.py deleted file mode 100644 index 68dc4d89701..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lros/_request_builders.py +++ /dev/null @@ -1,3109 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -@overload -def build_put200_succeeded_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put200_succeeded_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put200_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/put/200/succeeded" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_patch200_succeeded_ignore_headers_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request with location header. We - should not have any subsequent calls after receiving this first response. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to patch. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_patch200_succeeded_ignore_headers_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request with location header. We - should not have any subsequent calls after receiving this first response. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to patch. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_patch200_succeeded_ignore_headers_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request with location header. We - should not have any subsequent calls after receiving this first response. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to patch. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/patch/200/succeeded/ignoreheaders" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, **kwargs) - - -@overload -def build_patch201_retry_with_async_header_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running patch request, service returns a 201 to the initial request with async header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to patch. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_patch201_retry_with_async_header_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running patch request, service returns a 201 to the initial request with async header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to patch. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_patch201_retry_with_async_header_request(**kwargs: Any) -> HttpRequest: - """Long running patch request, service returns a 201 to the initial request with async header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to patch. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/patch/201/retry/onlyAsyncHeader" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, **kwargs) - - -@overload -def build_patch202_retry_with_async_and_location_header_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running patch request, service returns a 202 to the initial request with async and - location header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to patch. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_patch202_retry_with_async_and_location_header_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running patch request, service returns a 202 to the initial request with async and - location header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to patch. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_patch202_retry_with_async_and_location_header_request(**kwargs: Any) -> HttpRequest: - """Long running patch request, service returns a 202 to the initial request with async and - location header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to patch. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/patch/202/retry/asyncAndLocationHeader" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put201_succeeded_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put201_succeeded_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put201_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/put/201/succeeded" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_post202_list_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 202 with empty body to first request, returns a 200 - with body [{ 'id': '100', 'name': 'foo' }]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/list" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put200_succeeded_no_state_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - does not contain ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put200_succeeded_no_state_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - does not contain ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put200_succeeded_no_state_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - does not contain ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/put/200/succeeded/nostate" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put202_retry200_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 202 to the initial request, with a location header - that points to a polling URL that returns a 200 and an entity that doesn't contains - ProvisioningState. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put202_retry200_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 202 to the initial request, with a location header - that points to a polling URL that returns a 200 and an entity that doesn't contains - ProvisioningState. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put202_retry200_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 202 to the initial request, with a location header - that points to a polling URL that returns a 200 and an entity that doesn't contains - ProvisioningState. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/put/202/retry/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put201_creating_succeeded200_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put201_creating_succeeded200_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put201_creating_succeeded200_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/put/201/creating/succeeded/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put200_updating_succeeded204_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Updating’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put200_updating_succeeded204_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Updating’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put200_updating_succeeded204_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Updating’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/put/200/updating/succeeded/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put201_creating_failed200_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Created’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Failed’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put201_creating_failed200_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Created’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Failed’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put201_creating_failed200_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Created’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Failed’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/put/201/created/failed/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put200_acceptedcanceled200_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Canceled’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put200_acceptedcanceled200_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Canceled’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put200_acceptedcanceled200_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Canceled’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/put/200/accepted/canceled/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_no_header_in_retry_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 202 to the initial request with location header. - Subsequent calls to operation status do not contain location header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_no_header_in_retry_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 202 to the initial request with location header. - Subsequent calls to operation status do not contain location header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_no_header_in_retry_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 202 to the initial request with location header. - Subsequent calls to operation status do not contain location header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/put/noheader/202/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_retry_succeeded_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_retry_succeeded_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_retry_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/putasync/retry/succeeded" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_no_retry_succeeded_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_no_retry_succeeded_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_no_retry_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/putasync/noretry/succeeded" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_retry_failed_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_retry_failed_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_retry_failed_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/putasync/retry/failed" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_no_retrycanceled_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_no_retrycanceled_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_no_retrycanceled_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/putasync/noretry/canceled" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_no_header_in_retry_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 202 to the initial request with - Azure-AsyncOperation header. Subsequent calls to operation status do not contain - Azure-AsyncOperation header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_no_header_in_retry_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 202 to the initial request with - Azure-AsyncOperation header. Subsequent calls to operation status do not contain - Azure-AsyncOperation header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_no_header_in_retry_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 202 to the initial request with - Azure-AsyncOperation header. Subsequent calls to operation status do not contain - Azure-AsyncOperation header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/putasync/noheader/201/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_non_resource_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request with non resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: sku to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. - "name": "str" # Optional. - } - """ - - -@overload -def build_put_non_resource_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request with non resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: sku to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_non_resource_request(**kwargs: Any) -> HttpRequest: - """Long running put request with non resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: sku to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/putnonresource/202/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_non_resource_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request with non resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Sku to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. - "name": "str" # Optional. - } - """ - - -@overload -def build_put_async_non_resource_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request with non resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Sku to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_non_resource_request(**kwargs: Any) -> HttpRequest: - """Long running put request with non resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Sku to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/putnonresourceasync/202/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_sub_resource_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request with sub resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Sub Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Sub Resource Id. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - } - } - """ - - -@overload -def build_put_sub_resource_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request with sub resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Sub Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_sub_resource_request(**kwargs: Any) -> HttpRequest: - """Long running put request with sub resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Sub Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/putsubresource/202/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_sub_resource_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request with sub resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Sub Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Sub Resource Id. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - } - } - """ - - -@overload -def build_put_async_sub_resource_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request with sub resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Sub Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_sub_resource_request(**kwargs: Any) -> HttpRequest: - """Long running put request with sub resource. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Sub Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/putsubresourceasync/202/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_delete_provisioning202_accepted200_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Accepted’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/delete/provisioning/202/accepted/200/succeeded" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_provisioning202_deleting_failed200_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Failed’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/delete/provisioning/202/deleting/200/failed" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_provisioning202_deletingcanceled200_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Polls return this value until the last poll returns a - ‘200’ with ProvisioningState=’Canceled’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/delete/provisioning/202/deleting/200/canceled" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete204_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running delete succeeds and returns right away. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/delete/204/succeeded" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete202_retry200_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request. Polls return this - value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/delete/202/retry/200" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete202_no_retry204_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request. Polls return this - value until the last poll returns a ‘200’ with ProvisioningState=’Succeeded’. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/delete/202/noretry/204" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_no_header_in_retry_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a location header in the initial request. - Subsequent calls to operation status do not contain location header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/delete/noheader" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_async_no_header_in_retry_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns an Azure-AsyncOperation header in the initial - request. Subsequent calls to operation status do not contain Azure-AsyncOperation header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/deleteasync/noheader/202/204" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_async_retry_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request. Poll the endpoint - indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/deleteasync/retry/succeeded" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_async_no_retry_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request. Poll the endpoint - indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/deleteasync/noretry/succeeded" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_async_retry_failed_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request. Poll the endpoint - indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/deleteasync/retry/failed" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_async_retrycanceled_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request. Poll the endpoint - indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/deleteasync/retry/canceled" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_post200_with_payload_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with 'Location' - header. Poll returns a 200 with a response body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/post/payload/200" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post202_retry200_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with 'Location' and - 'Retry-After' headers, Polls return a 200 with a response body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post202_retry200_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with 'Location' and - 'Retry-After' headers, Polls return a 200 with a response body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post202_retry200_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with 'Location' and - 'Retry-After' headers, Polls return a 200 with a response body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/post/202/retry/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post202_no_retry204_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with 'Location' - header, 204 with noresponse body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post202_no_retry204_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with 'Location' - header, 204 with noresponse body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post202_no_retry204_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with 'Location' - header, 204 with noresponse body after success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/post/202/noretry/204" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_double_headers_final_location_get_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request with both Location and - Azure-Async header. Poll Azure-Async and it's success. Should poll Location to get the final - object. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/LROPostDoubleHeadersFinalLocationGet" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_double_headers_final_azure_header_get_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request with both Location and - Azure-Async header. Poll Azure-Async and it's success. Should NOT poll Location to get the - final object. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/LROPostDoubleHeadersFinalAzureHeaderGet" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_double_headers_final_azure_header_get_default_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request with both Location and - Azure-Async header. Poll Azure-Async and it's success. Should NOT poll Location to get the - final object if you support initial Autorest behavior. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/LROPostDoubleHeadersFinalAzureHeaderGetDefault" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_async_retry_succeeded_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post_async_retry_succeeded_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_async_retry_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/postasync/retry/succeeded" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_async_no_retry_succeeded_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post_async_no_retry_succeeded_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_async_no_retry_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/postasync/noretry/succeeded" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_async_retry_failed_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post_async_retry_failed_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_async_retry_failed_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/postasync/retry/failed" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_async_retrycanceled_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post_async_retrycanceled_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_async_retrycanceled_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/postasync/retry/canceled" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lrosads/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lrosads/__init__.py deleted file mode 100644 index 276eb5712cd..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lrosads/__init__.py +++ /dev/null @@ -1,63 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_put_non_retry400_request -from ._request_builders import build_put_non_retry201_creating400_request -from ._request_builders import build_put_non_retry201_creating400_invalid_json_request -from ._request_builders import build_put_async_relative_retry400_request -from ._request_builders import build_delete_non_retry400_request -from ._request_builders import build_delete202_non_retry400_request -from ._request_builders import build_delete_async_relative_retry400_request -from ._request_builders import build_post_non_retry400_request -from ._request_builders import build_post202_non_retry400_request -from ._request_builders import build_post_async_relative_retry400_request -from ._request_builders import build_put_error201_no_provisioning_state_payload_request -from ._request_builders import build_put_async_relative_retry_no_status_request -from ._request_builders import build_put_async_relative_retry_no_status_payload_request -from ._request_builders import build_delete204_succeeded_request -from ._request_builders import build_delete_async_relative_retry_no_status_request -from ._request_builders import build_post202_no_location_request -from ._request_builders import build_post_async_relative_retry_no_payload_request -from ._request_builders import build_put200_invalid_json_request -from ._request_builders import build_put_async_relative_retry_invalid_header_request -from ._request_builders import build_put_async_relative_retry_invalid_json_polling_request -from ._request_builders import build_delete202_retry_invalid_header_request -from ._request_builders import build_delete_async_relative_retry_invalid_header_request -from ._request_builders import build_delete_async_relative_retry_invalid_json_polling_request -from ._request_builders import build_post202_retry_invalid_header_request -from ._request_builders import build_post_async_relative_retry_invalid_header_request -from ._request_builders import build_post_async_relative_retry_invalid_json_polling_request - -__all__ = [ - "build_put_non_retry400_request", - "build_put_non_retry201_creating400_request", - "build_put_non_retry201_creating400_invalid_json_request", - "build_put_async_relative_retry400_request", - "build_delete_non_retry400_request", - "build_delete202_non_retry400_request", - "build_delete_async_relative_retry400_request", - "build_post_non_retry400_request", - "build_post202_non_retry400_request", - "build_post_async_relative_retry400_request", - "build_put_error201_no_provisioning_state_payload_request", - "build_put_async_relative_retry_no_status_request", - "build_put_async_relative_retry_no_status_payload_request", - "build_delete204_succeeded_request", - "build_delete_async_relative_retry_no_status_request", - "build_post202_no_location_request", - "build_post_async_relative_retry_no_payload_request", - "build_put200_invalid_json_request", - "build_put_async_relative_retry_invalid_header_request", - "build_put_async_relative_retry_invalid_json_polling_request", - "build_delete202_retry_invalid_header_request", - "build_delete_async_relative_retry_invalid_header_request", - "build_delete_async_relative_retry_invalid_json_polling_request", - "build_post202_retry_invalid_header_request", - "build_post_async_relative_retry_invalid_header_request", - "build_post_async_relative_retry_invalid_json_polling_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lrosads/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lrosads/_request_builders.py deleted file mode 100644 index 447bdf1ba33..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/lrolowlevel/rest/lrosads/_request_builders.py +++ /dev/null @@ -1,2001 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -@overload -def build_put_non_retry400_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 400 to the initial request. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_non_retry400_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 400 to the initial request. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_non_retry400_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 400 to the initial request. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/nonretryerror/put/400" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_non_retry201_creating400_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and - 201 response code. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_non_retry201_creating400_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and - 201 response code. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_non_retry201_creating400_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and - 201 response code. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/nonretryerror/put/201/creating/400" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_non_retry201_creating400_invalid_json_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and - 201 response code. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_non_retry201_creating400_invalid_json_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and - 201 response code. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_non_retry201_creating400_invalid_json_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a Product with 'ProvisioningState' = 'Creating' and - 201 response code. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/nonretryerror/put/201/creating/400/invalidjson" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_relative_retry400_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 with ProvisioningState=’Creating’. Poll the - endpoint indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_relative_retry400_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 with ProvisioningState=’Creating’. Poll the - endpoint indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_relative_retry400_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 with ProvisioningState=’Creating’. Poll the - endpoint indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/nonretryerror/putasync/retry/400" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_delete_non_retry400_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 400 with an error body. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/nonretryerror/delete/400" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete202_non_retry400_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 with a location header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/nonretryerror/delete/202/retry/400" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_async_relative_retry400_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request. Poll the endpoint - indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/nonretryerror/deleteasync/retry/400" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_non_retry400_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 400 with no error body. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post_non_retry400_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 400 with no error body. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_non_retry400_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 400 with no error body. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/nonretryerror/post/400" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post202_non_retry400_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 with a location header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post202_non_retry400_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 with a location header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post202_non_retry400_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 with a location header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/nonretryerror/post/202/retry/400" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_async_relative_retry400_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request Poll the endpoint - indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post_async_relative_retry400_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request Poll the endpoint - indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_async_relative_retry400_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request Poll the endpoint - indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/nonretryerror/postasync/retry/400" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_error201_no_provisioning_state_payload_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_error201_no_provisioning_state_payload_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_error201_no_provisioning_state_payload_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 201 to the initial request with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/put/201/noprovisioningstatepayload" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_relative_retry_no_status_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_relative_retry_no_status_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_relative_retry_no_status_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/putasync/retry/nostatus" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_relative_retry_no_status_payload_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_relative_retry_no_status_payload_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_relative_retry_no_status_payload_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/putasync/retry/nostatuspayload" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_delete204_succeeded_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 204 to the initial request, indicating success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/delete/204/nolocation" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_async_relative_retry_no_status_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request. Poll the endpoint - indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/deleteasync/retry/nostatus" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post202_no_location_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, without a location - header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post202_no_location_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, without a location - header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post202_no_location_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, without a location - header. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/post/202/nolocation" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_async_relative_retry_no_payload_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post_async_relative_retry_no_payload_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_async_relative_retry_no_payload_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/postasync/retry/nopayload" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put200_invalid_json_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that is - not a valid json. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put200_invalid_json_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that is - not a valid json. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put200_invalid_json_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that is - not a valid json. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/put/200/invalidjson" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_relative_retry_invalid_header_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation - header is invalid. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_relative_retry_invalid_header_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation - header is invalid. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_relative_retry_invalid_header_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation - header is invalid. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/putasync/retry/invalidheader" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_async_relative_retry_invalid_json_polling_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_put_async_relative_retry_invalid_json_polling_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_async_relative_retry_invalid_json_polling_request(**kwargs: Any) -> HttpRequest: - """Long running put request, service returns a 200 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/putasync/retry/invalidjsonpolling" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_delete202_retry_invalid_header_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request receing a reponse - with an invalid 'Location' and 'Retry-After' headers. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/delete/202/retry/invalidheader" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_async_relative_retry_invalid_header_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request. The endpoint - indicated in the Azure-AsyncOperation header is invalid. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/deleteasync/retry/invalidheader" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -def build_delete_async_relative_retry_invalid_json_polling_request(**kwargs: Any) -> HttpRequest: - """Long running delete request, service returns a 202 to the initial request. Poll the endpoint - indicated in the Azure-AsyncOperation header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/deleteasync/retry/invalidjsonpolling" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post202_retry_invalid_header_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with invalid - 'Location' and 'Retry-After' headers. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post202_retry_invalid_header_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with invalid - 'Location' and 'Retry-After' headers. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post202_retry_invalid_header_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with invalid - 'Location' and 'Retry-After' headers. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/post/202/retry/invalidheader" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_async_relative_retry_invalid_header_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation - header is invalid. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post_async_relative_retry_invalid_header_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation - header is invalid. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_async_relative_retry_invalid_header_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. The endpoint indicated in the Azure-AsyncOperation - header is invalid. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/postasync/retry/invalidheader" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_async_relative_retry_invalid_json_polling_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "provisioningState": "str", # Optional. - "provisioningStateValues": "str" # Optional. Known values are: - "Succeeded", "Failed", "canceled", "Accepted", "Creating", "Created", - "Updating", "Updated", "Deleting", "Deleted", and "OK". - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - """ - - -@overload -def build_post_async_relative_retry_invalid_json_polling_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_async_relative_retry_invalid_json_polling_request(**kwargs: Any) -> HttpRequest: - """Long running post request, service returns a 202 to the initial request, with an entity that - contains ProvisioningState=’Creating’. Poll the endpoint indicated in the Azure-AsyncOperation - header for operation status. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Product to put. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lro/error/postasync/retry/invalidjsonpolling" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/setup.py deleted file mode 100644 index 5f093bc0009..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestlongrunningoperationtestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestLongRunningOperationTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-mgmt-core<2.0.0,>=1.3.0", - ], - long_description="""\ - Long-running Operation for AutoRest. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/__init__.py deleted file mode 100644 index db475579c4b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import LROWithParamaterizedEndpoints -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["LROWithParamaterizedEndpoints"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_client.py deleted file mode 100644 index 5d849658bdb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_client.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import LROWithParamaterizedEndpointsConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class LROWithParamaterizedEndpoints: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param host: A string value that is used as a global part of the parameterized host. Pass in - 'host:3000' to pass test. Default value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - _endpoint = "http://{accountName}{host}" - self._config = LROWithParamaterizedEndpointsConfiguration(host=host, **kwargs) - self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `lrowithparameterizedendpointslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from lrowithparameterizedendpointslowlevel.rest import build_poll_with_parameterized_endpoints_request - >>> request = build_poll_with_parameterized_endpoints_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> LROWithParamaterizedEndpoints - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_configuration.py deleted file mode 100644 index 98fc24a6944..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_configuration.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class LROWithParamaterizedEndpointsConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for LROWithParamaterizedEndpoints. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param host: A string value that is used as a global part of the parameterized host. Pass in - 'host:3000' to pass test. Default value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - super(LROWithParamaterizedEndpointsConfiguration, self).__init__(**kwargs) - if host is None: - raise ValueError("Parameter 'host' must not be None.") - - self.host = host - kwargs.setdefault("sdk_moniker", "lrowithparamaterizedendpoints/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_vendor.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/__init__.py deleted file mode 100644 index ba2eeac8e14..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import LROWithParamaterizedEndpoints - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["LROWithParamaterizedEndpoints"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_client.py deleted file mode 100644 index 88fd8578ed1..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_client.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import LROWithParamaterizedEndpointsConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class LROWithParamaterizedEndpoints: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param host: A string value that is used as a global part of the parameterized host. Pass in - 'host:3000' to pass test. Default value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - _endpoint = "http://{accountName}{host}" - self._config = LROWithParamaterizedEndpointsConfiguration(host=host, **kwargs) - self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `lrowithparameterizedendpointslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from lrowithparameterizedendpointslowlevel.rest import build_poll_with_parameterized_endpoints_request - >>> request = build_poll_with_parameterized_endpoints_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "LROWithParamaterizedEndpoints": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_configuration.py deleted file mode 100644 index 7fb84709e51..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_configuration.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class LROWithParamaterizedEndpointsConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for LROWithParamaterizedEndpoints. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param host: A string value that is used as a global part of the parameterized host. Pass in - 'host:3000' to pass test. Default value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - super(LROWithParamaterizedEndpointsConfiguration, self).__init__(**kwargs) - if host is None: - raise ValueError("Parameter 'host' must not be None.") - - self.host = host - kwargs.setdefault("sdk_moniker", "lrowithparamaterizedendpoints/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/rest/__init__.py deleted file mode 100644 index 08cf0a8d2e6..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/rest/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_poll_with_parameterized_endpoints_request -from ._request_builders import build_poll_with_constant_parameterized_endpoints_request - -__all__ = [ - "build_poll_with_parameterized_endpoints_request", - "build_poll_with_constant_parameterized_endpoints_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/rest/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/rest/_request_builders.py deleted file mode 100644 index d668c6576a9..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/lrowithparameterizedendpointslowlevel/rest/_request_builders.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer -from .._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_poll_with_parameterized_endpoints_request(**kwargs: Any) -> HttpRequest: - """Poll with method and client level parameters in endpoint. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lroParameterizedEndpoints" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_poll_with_constant_parameterized_endpoints_request(**kwargs: Any) -> HttpRequest: - """Poll with method and client level parameters in endpoint, with a constant value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword constant_parameter: Next link for the list operation. Default value is "iAmConstant". - Note that overriding this default value may result in unsupported behavior. - :paramtype constant_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - constant_parameter = kwargs.pop("constant_parameter", "iAmConstant") # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/lroConstantParameterizedEndpoints/{constantParameter}" - path_format_arguments = { - "constantParameter": _SERIALIZER.url("constant_parameter", constant_parameter, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/setup.py deleted file mode 100644 index 1599be143b6..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "lrowithparamaterizedendpoints" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="LROWithParamaterizedEndpoints", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/__init__.py deleted file mode 100644 index 8990f91af4a..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestPagingTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestPagingTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_client.py deleted file mode 100644 index 866903bc0d2..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestPagingTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestPagingTestService: # pylint: disable=client-accepts-api-version-keyword - """Long-running Operation for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestPagingTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `paginglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from paginglowlevel.rest import paging - >>> request = paging.build_get_no_item_name_pages_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestPagingTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_configuration.py deleted file mode 100644 index 3352eae9c24..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestPagingTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestPagingTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestPagingTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestpagingtestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_vendor.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/__init__.py deleted file mode 100644 index 33a76dc2296..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestPagingTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestPagingTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_client.py deleted file mode 100644 index d57632efd3b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestPagingTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestPagingTestService: # pylint: disable=client-accepts-api-version-keyword - """Long-running Operation for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestPagingTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `paginglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from paginglowlevel.rest import paging - >>> request = paging.build_get_no_item_name_pages_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestPagingTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_configuration.py deleted file mode 100644 index b095035214a..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestPagingTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestPagingTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestPagingTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestpagingtestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/paging/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/paging/__init__.py deleted file mode 100644 index 4d6ad850875..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/paging/__init__.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_no_item_name_pages_request -from ._request_builders import build_get_null_next_link_name_pages_request -from ._request_builders import build_get_single_pages_request -from ._request_builders import build_first_response_empty_request -from ._request_builders import build_get_multiple_pages_request -from ._request_builders import build_get_with_query_params_request -from ._request_builders import build_next_operation_with_query_params_request -from ._request_builders import build_duplicate_params_request -from ._request_builders import build_get_odata_multiple_pages_request -from ._request_builders import build_get_multiple_pages_with_offset_request -from ._request_builders import build_get_multiple_pages_retry_first_request -from ._request_builders import build_get_multiple_pages_retry_second_request -from ._request_builders import build_get_single_pages_failure_request -from ._request_builders import build_get_multiple_pages_failure_request -from ._request_builders import build_get_multiple_pages_failure_uri_request -from ._request_builders import build_get_multiple_pages_fragment_next_link_request -from ._request_builders import build_next_fragment_request -from ._request_builders import build_get_multiple_pages_fragment_with_grouping_next_link_request -from ._request_builders import build_next_fragment_with_grouping_request -from ._request_builders import build_get_multiple_pages_lro_request -from ._request_builders import build_get_paging_model_with_item_name_with_xms_client_name_request - -__all__ = [ - "build_get_no_item_name_pages_request", - "build_get_null_next_link_name_pages_request", - "build_get_single_pages_request", - "build_first_response_empty_request", - "build_get_multiple_pages_request", - "build_get_with_query_params_request", - "build_next_operation_with_query_params_request", - "build_duplicate_params_request", - "build_get_odata_multiple_pages_request", - "build_get_multiple_pages_with_offset_request", - "build_get_multiple_pages_retry_first_request", - "build_get_multiple_pages_retry_second_request", - "build_get_single_pages_failure_request", - "build_get_multiple_pages_failure_request", - "build_get_multiple_pages_failure_uri_request", - "build_get_multiple_pages_fragment_next_link_request", - "build_next_fragment_request", - "build_get_multiple_pages_fragment_with_grouping_next_link_request", - "build_next_fragment_with_grouping_request", - "build_get_multiple_pages_lro_request", - "build_get_paging_model_with_item_name_with_xms_client_name_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/paging/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/paging/_request_builders.py deleted file mode 100644 index fb70dadfb7d..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/paginglowlevel/rest/paging/_request_builders.py +++ /dev/null @@ -1,715 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_no_item_name_pages_request(**kwargs: Any) -> HttpRequest: - """A paging operation that must return result of the default 'value' node. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/noitemname" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_null_next_link_name_pages_request(**kwargs: Any) -> HttpRequest: - """A paging operation that must ignore any kind of nextLink, and stop after page 1. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/nullnextlink" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_single_pages_request(**kwargs: Any) -> HttpRequest: - """A paging operation that finishes on the first call without a nextlink. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/single" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_first_response_empty_request(**kwargs: Any) -> HttpRequest: - """A paging operation whose first response's items list is empty, but still returns a next link. - Second (and final) call, will give you an items list of 1. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/firstResponseEmpty/1" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_multiple_pages_request( - *, client_request_id: Optional[str] = None, maxresults: Optional[int] = None, timeout: int = 30, **kwargs: Any -) -> HttpRequest: - """A paging operation that includes a nextLink that has 10 pages. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword client_request_id: Default value is None. - :paramtype client_request_id: str - :keyword maxresults: Sets the maximum number of items to return in the response. Default value - is None. - :paramtype maxresults: int - :keyword timeout: Sets the maximum time that the server can spend processing the request, in - seconds. The default is 30 seconds. Default value is 30. - :paramtype timeout: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple" - - # Construct headers - if client_request_id is not None: - _headers["client-request-id"] = _SERIALIZER.header("client_request_id", client_request_id, "str") - if maxresults is not None: - _headers["maxresults"] = _SERIALIZER.header("maxresults", maxresults, "int") - if timeout is not None: - _headers["timeout"] = _SERIALIZER.header("timeout", timeout, "int") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_with_query_params_request(*, required_query_parameter: int, **kwargs: Any) -> HttpRequest: - """A paging operation that includes a next operation. It has a different query parameter from it's - next operation nextOperationWithQueryParams. Returns a ProductResult. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword required_query_parameter: A required integer query parameter. Put in value '100' to - pass test. Required. - :paramtype required_query_parameter: int - :keyword query_constant: A constant. Must be True and will be passed as a query parameter to - nextOperationWithQueryParams. Default value is True. Note that overriding this default value - may result in unsupported behavior. - :paramtype query_constant: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - query_constant = kwargs.pop("query_constant", _params.pop("queryConstant", True)) # type: bool - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/getWithQueryParams" - - # Construct parameters - _params["requiredQueryParameter"] = _SERIALIZER.query("required_query_parameter", required_query_parameter, "int") - _params["queryConstant"] = _SERIALIZER.query("query_constant", query_constant, "bool") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_next_operation_with_query_params_request(**kwargs: Any) -> HttpRequest: - """Next operation for getWithQueryParams. Pass in next=True to pass test. Returns a ProductResult - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword query_constant: A constant. Must be True Default value is True. Note that overriding - this default value may result in unsupported behavior. - :paramtype query_constant: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - query_constant = kwargs.pop("query_constant", _params.pop("queryConstant", True)) # type: bool - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/nextOperationWithQueryParams" - - # Construct parameters - _params["queryConstant"] = _SERIALIZER.query("query_constant", query_constant, "bool") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_duplicate_params_request(*, filter: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Define ``filter`` as a query param for all calls. However, the returned next link will also - include the ``filter`` as part of it. Make sure you don't end up duplicating the ``filter`` - param in the url sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword filter: OData filter options. Pass in 'foo'. Default value is None. - :paramtype filter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/duplicateParams/1" - - # Construct parameters - if filter is not None: - _params["$filter"] = _SERIALIZER.query("filter", filter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_odata_multiple_pages_request( - *, client_request_id: Optional[str] = None, maxresults: Optional[int] = None, timeout: int = 30, **kwargs: Any -) -> HttpRequest: - """A paging operation that includes a nextLink in odata format that has 10 pages. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword client_request_id: Default value is None. - :paramtype client_request_id: str - :keyword maxresults: Sets the maximum number of items to return in the response. Default value - is None. - :paramtype maxresults: int - :keyword timeout: Sets the maximum time that the server can spend processing the request, in - seconds. The default is 30 seconds. Default value is 30. - :paramtype timeout: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/odata" - - # Construct headers - if client_request_id is not None: - _headers["client-request-id"] = _SERIALIZER.header("client_request_id", client_request_id, "str") - if maxresults is not None: - _headers["maxresults"] = _SERIALIZER.header("maxresults", maxresults, "int") - if timeout is not None: - _headers["timeout"] = _SERIALIZER.header("timeout", timeout, "int") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_multiple_pages_with_offset_request( - offset: int, - *, - client_request_id: Optional[str] = None, - maxresults: Optional[int] = None, - timeout: int = 30, - **kwargs: Any -) -> HttpRequest: - """A paging operation that includes a nextLink that has 10 pages. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param offset: Offset of return value. Required. - :type offset: int - :keyword client_request_id: Default value is None. - :paramtype client_request_id: str - :keyword maxresults: Sets the maximum number of items to return in the response. Default value - is None. - :paramtype maxresults: int - :keyword timeout: Sets the maximum time that the server can spend processing the request, in - seconds. The default is 30 seconds. Default value is 30. - :paramtype timeout: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/withpath/{offset}" - path_format_arguments = { - "offset": _SERIALIZER.url("offset", offset, "int"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - if client_request_id is not None: - _headers["client-request-id"] = _SERIALIZER.header("client_request_id", client_request_id, "str") - if maxresults is not None: - _headers["maxresults"] = _SERIALIZER.header("maxresults", maxresults, "int") - if timeout is not None: - _headers["timeout"] = _SERIALIZER.header("timeout", timeout, "int") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_multiple_pages_retry_first_request(**kwargs: Any) -> HttpRequest: - """A paging operation that fails on the first call with 500 and then retries and then get a - response including a nextLink that has 10 pages. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/retryfirst" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_multiple_pages_retry_second_request(**kwargs: Any) -> HttpRequest: - """A paging operation that includes a nextLink that has 10 pages, of which the 2nd call fails - first with 500. The client should retry and finish all 10 pages eventually. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/retrysecond" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_single_pages_failure_request(**kwargs: Any) -> HttpRequest: - """A paging operation that receives a 400 on the first call. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/single/failure" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_multiple_pages_failure_request(**kwargs: Any) -> HttpRequest: - """A paging operation that receives a 400 on the second call. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/failure" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_multiple_pages_failure_uri_request(**kwargs: Any) -> HttpRequest: - """A paging operation that receives an invalid nextLink. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/failureuri" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_multiple_pages_fragment_next_link_request(tenant: str, *, api_version: str, **kwargs: Any) -> HttpRequest: - """A paging operation that doesn't return a full URL, just a fragment. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param tenant: Sets the tenant to use. Required. - :type tenant: str - :keyword api_version: Sets the api version to use. Required. - :paramtype api_version: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/fragment/{tenant}" - path_format_arguments = { - "tenant": _SERIALIZER.url("tenant", tenant, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api_version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_next_fragment_request(tenant: str, next_link: str, *, api_version: str, **kwargs: Any) -> HttpRequest: - """A paging operation that doesn't return a full URL, just a fragment - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param tenant: Sets the tenant to use. Required. - :type tenant: str - :param next_link: Next link for list operation. Required. - :type next_link: str - :keyword api_version: Sets the api version to use. Required. - :paramtype api_version: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/fragment/{tenant}/{nextLink}" - path_format_arguments = { - "tenant": _SERIALIZER.url("tenant", tenant, "str"), - "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api_version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_multiple_pages_fragment_with_grouping_next_link_request( - tenant: str, *, api_version: str, **kwargs: Any -) -> HttpRequest: - """A paging operation that doesn't return a full URL, just a fragment with parameters grouped. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param tenant: Sets the tenant to use. Required. - :type tenant: str - :keyword api_version: Sets the api version to use. Required. - :paramtype api_version: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/fragmentwithgrouping/{tenant}" - path_format_arguments = { - "tenant": _SERIALIZER.url("tenant", tenant, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api_version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_next_fragment_with_grouping_request( - tenant: str, next_link: str, *, api_version: str, **kwargs: Any -) -> HttpRequest: - """A paging operation that doesn't return a full URL, just a fragment - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param tenant: Sets the tenant to use. Required. - :type tenant: str - :param next_link: Next link for list operation. Required. - :type next_link: str - :keyword api_version: Sets the api version to use. Required. - :paramtype api_version: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/fragmentwithgrouping/{tenant}/{nextLink}" - path_format_arguments = { - "tenant": _SERIALIZER.url("tenant", tenant, "str"), - "nextLink": _SERIALIZER.url("next_link", next_link, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api_version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_multiple_pages_lro_request( - *, client_request_id: Optional[str] = None, maxresults: Optional[int] = None, timeout: int = 30, **kwargs: Any -) -> HttpRequest: - """A long-running paging operation that includes a nextLink that has 10 pages. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword client_request_id: Default value is None. - :paramtype client_request_id: str - :keyword maxresults: Sets the maximum number of items to return in the response. Default value - is None. - :paramtype maxresults: int - :keyword timeout: Sets the maximum time that the server can spend processing the request, in - seconds. The default is 30 seconds. Default value is 30. - :paramtype timeout: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/multiple/lro" - - # Construct headers - if client_request_id is not None: - _headers["client-request-id"] = _SERIALIZER.header("client_request_id", client_request_id, "str") - if maxresults is not None: - _headers["maxresults"] = _SERIALIZER.header("maxresults", maxresults, "int") - if timeout is not None: - _headers["timeout"] = _SERIALIZER.header("timeout", timeout, "int") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_get_paging_model_with_item_name_with_xms_client_name_request(**kwargs: Any) -> HttpRequest: - """A paging operation that returns a paging model whose item name is is overriden by - x-ms-client-name 'indexes'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paging/itemNameWithXMSClientName" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/setup.py deleted file mode 100644 index b29591b0a79..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/PagingLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestpagingtestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestPagingTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Long-running Operation for AutoRest. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/setup.py deleted file mode 100644 index dfc9076af80..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "storagemanagementclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="StorageManagementClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-mgmt-core<2.0.0,>=1.3.0", - ], - long_description="""\ - StorageManagementClient. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/__init__.py deleted file mode 100644 index f67009c0404..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import StorageManagementClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["StorageManagementClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_client.py deleted file mode 100644 index ddc47e89c67..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_client.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core.rest import HttpRequest, HttpResponse -from azure.mgmt.core import ARMPipelineClient - -from ._configuration import StorageManagementClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials import TokenCredential - - -class StorageManagementClient: # pylint: disable=client-accepts-api-version-keyword - """StorageManagementClient. - - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword endpoint: Service URL. Default value is "https://management.azure.com". - :paramtype endpoint: str - :keyword api_version: Api Version. Default value is "2015-05-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - subscription_id: str, - credential: "TokenCredential", - *, - endpoint: str = "https://management.azure.com", - **kwargs: Any - ) -> None: - self._config = StorageManagementClientConfiguration( - subscription_id=subscription_id, credential=credential, **kwargs - ) - self._client = ARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `storagelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from storagelowlevel.rest import storage_accounts - >>> request = storage_accounts.build_check_name_availability_request(subscription_id, json=json, content_type=content_type, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> StorageManagementClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_configuration.py deleted file mode 100644 index 8fdef95ede3..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_configuration.py +++ /dev/null @@ -1,70 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import TokenCredential - - -class StorageManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for StorageManagementClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: Api Version. Default value is "2015-05-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, subscription_id: str, credential: "TokenCredential", **kwargs: Any) -> None: - super(StorageManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2015-05-01-preview") # type: str - - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.subscription_id = subscription_id - self.credential = credential - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "storagemanagementclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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.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 - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_vendor.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/__init__.py deleted file mode 100644 index 595da8efef8..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import StorageManagementClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["StorageManagementClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_client.py deleted file mode 100644 index aeb339314ad..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_client.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.mgmt.core import AsyncARMPipelineClient - -from .._serialization import Deserializer, Serializer -from ._configuration import StorageManagementClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials_async import AsyncTokenCredential - - -class StorageManagementClient: # pylint: disable=client-accepts-api-version-keyword - """StorageManagementClient. - - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword endpoint: Service URL. Default value is "https://management.azure.com". - :paramtype endpoint: str - :keyword api_version: Api Version. Default value is "2015-05-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - subscription_id: str, - credential: "AsyncTokenCredential", - *, - endpoint: str = "https://management.azure.com", - **kwargs: Any - ) -> None: - self._config = StorageManagementClientConfiguration( - subscription_id=subscription_id, credential=credential, **kwargs - ) - self._client = AsyncARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `storagelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from storagelowlevel.rest import storage_accounts - >>> request = storage_accounts.build_check_name_availability_request(subscription_id, json=json, content_type=content_type, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "StorageManagementClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_configuration.py deleted file mode 100644 index ecb1b3d2065..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_configuration.py +++ /dev/null @@ -1,67 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials_async import AsyncTokenCredential - - -class StorageManagementClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for StorageManagementClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: Api Version. Default value is "2015-05-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, subscription_id: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(StorageManagementClientConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2015-05-01-preview") # type: str - - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.subscription_id = subscription_id - self.credential = credential - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "storagemanagementclient/{}".format(VERSION)) - 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") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/storage_accounts/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/storage_accounts/__init__.py deleted file mode 100644 index 2386f8655b7..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/storage_accounts/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_check_name_availability_request -from ._request_builders import build_create_request -from ._request_builders import build_delete_request -from ._request_builders import build_get_properties_request -from ._request_builders import build_update_request -from ._request_builders import build_list_keys_request -from ._request_builders import build_list_request -from ._request_builders import build_list_by_resource_group_request -from ._request_builders import build_regenerate_key_request - -__all__ = [ - "build_check_name_availability_request", - "build_create_request", - "build_delete_request", - "build_get_properties_request", - "build_update_request", - "build_list_keys_request", - "build_list_request", - "build_list_by_resource_group_request", - "build_regenerate_key_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/storage_accounts/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/storage_accounts/_request_builders.py deleted file mode 100644 index 550a0044ad7..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/storage_accounts/_request_builders.py +++ /dev/null @@ -1,839 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -@overload -def build_check_name_availability_request( - subscription_id: str, *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Checks that account name is valid and is not in use. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword json: The name of the storage account within the specified resource group. Storage - account names must be between 3 and 24 characters in length and use numbers and lower-case - letters only. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "name": "str", # Required. - "type": "Microsoft.Storage/storageAccounts" # Optional. Default value is - "Microsoft.Storage/storageAccounts". - } - """ - - -@overload -def build_check_name_availability_request( - subscription_id: str, *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Checks that account name is valid and is not in use. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword content: The name of the storage account within the specified resource group. Storage - account names must be between 3 and 24 characters in length and use numbers and lower-case - letters only. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'text/json'. Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_check_name_availability_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """Checks that account name is valid and is not in use. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword json: The name of the storage account within the specified resource group. Storage - account names must be between 3 and 24 characters in length and use numbers and lower-case - letters only. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json', - 'text/json'. Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-05-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Storage/checkNameAvailability" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -@overload -def build_create_request( - resource_group_name: str, - account_name: str, - subscription_id: str, - *, - json: JSON, - content_type: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - """Asynchronously creates a new storage account with the specified parameters. Existing accounts - cannot be updated with this API and should instead use the Update Storage Account API. If an - account is already created and subsequent PUT request is issued with exact same set of - properties, then HTTP 200 would be returned. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account within the specified resource group. - Storage account names must be between 3 and 24 characters in length and use numbers and - lower-case letters only. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword json: The parameters to provide for the created account. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Resource location. Required. - "name": "str", # Optional. Resource name. - "properties": { - "accountType": "str" # Optional. Gets or sets the account type. - Known values are: "Standard_LRS", "Standard_ZRS", "Standard_GRS", - "Standard_RAGRS", and "Premium_LRS". - }, - "tags": { - "str": "str" # Optional. Resource tags. - }, - "type": "str" # Optional. Resource type. - } - """ - - -@overload -def build_create_request( - resource_group_name: str, - account_name: str, - subscription_id: str, - *, - content: IO, - content_type: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - """Asynchronously creates a new storage account with the specified parameters. Existing accounts - cannot be updated with this API and should instead use the Update Storage Account API. If an - account is already created and subsequent PUT request is issued with exact same set of - properties, then HTTP 200 would be returned. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account within the specified resource group. - Storage account names must be between 3 and 24 characters in length and use numbers and - lower-case letters only. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword content: The parameters to provide for the created account. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'text/json'. Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_create_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - """Asynchronously creates a new storage account with the specified parameters. Existing accounts - cannot be updated with this API and should instead use the Update Storage Account API. If an - account is already created and subsequent PUT request is issued with exact same set of - properties, then HTTP 200 would be returned. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account within the specified resource group. - Storage account names must be between 3 and 24 characters in length and use numbers and - lower-case letters only. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword json: The parameters to provide for the created account. Is either a model type or a - IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json', - 'text/json'. Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-05-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}" # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), - "accountName": _SERIALIZER.url("account_name", account_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_delete_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - """Deletes a storage account in Microsoft Azure. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account within the specified resource group. - Storage account names must be between 3 and 24 characters in length and use numbers and - lower-case letters only. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-05-01-preview")) # type: str - # Construct URL - _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}" # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), - "accountName": _SERIALIZER.url("account_name", account_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - return HttpRequest(method="DELETE", url=_url, params=_params, **kwargs) - - -def build_get_properties_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - """Returns the properties for the specified storage account including but not limited to name, - account type, location, and account status. The ListKeys operation should be used to retrieve - storage keys. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account within the specified resource group. - Storage account names must be between 3 and 24 characters in length and use numbers and - lower-case letters only. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-05-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}" # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), - "accountName": _SERIALIZER.url("account_name", account_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -@overload -def build_update_request( - resource_group_name: str, - account_name: str, - subscription_id: str, - *, - json: JSON, - content_type: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - """Updates the account type or tags for a storage account. It can also be used to add a custom - domain (note that custom domains cannot be added via the Create operation). Only one custom - domain is supported per storage account. This API can only be used to update one of tags, - accountType, or customDomain per call. To update multiple of these properties, call the API - multiple times with one change per call. This call does not change the storage keys for the - account. If you want to change storage account keys, use the RegenerateKey operation. The - location and name of the storage account cannot be changed after creation. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account within the specified resource group. - Storage account names must be between 3 and 24 characters in length and use numbers and - lower-case letters only. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword json: The parameters to update on the account. Note that only one property can be - changed at a time using this API. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. Resource Id. - "location": "str", # Resource location. Required. - "name": "str", # Optional. Resource name. - "properties": { - "accountType": "str", # Optional. Gets or sets the account type. - Note that StandardZRS and PremiumLRS accounts cannot be changed to other - account types, and other account types cannot be changed to StandardZRS or - PremiumLRS. Known values are: "Standard_LRS", "Standard_ZRS", "Standard_GRS", - "Standard_RAGRS", and "Premium_LRS". - "customDomain": { - "name": "str", # Optional. Gets or sets the custom domain - name. Name is the CNAME source. - "useSubDomain": bool # Optional. Indicates whether indirect - CName validation is enabled. Default value is false. This should only be - set on updates. - } - }, - "tags": { - "str": "str" # Optional. Resource tags. - }, - "type": "str" # Optional. Resource type. - } - """ - - -@overload -def build_update_request( - resource_group_name: str, - account_name: str, - subscription_id: str, - *, - content: IO, - content_type: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - """Updates the account type or tags for a storage account. It can also be used to add a custom - domain (note that custom domains cannot be added via the Create operation). Only one custom - domain is supported per storage account. This API can only be used to update one of tags, - accountType, or customDomain per call. To update multiple of these properties, call the API - multiple times with one change per call. This call does not change the storage keys for the - account. If you want to change storage account keys, use the RegenerateKey operation. The - location and name of the storage account cannot be changed after creation. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account within the specified resource group. - Storage account names must be between 3 and 24 characters in length and use numbers and - lower-case letters only. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword content: The parameters to update on the account. Note that only one property can be - changed at a time using this API. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'text/json'. Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_update_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - """Updates the account type or tags for a storage account. It can also be used to add a custom - domain (note that custom domains cannot be added via the Create operation). Only one custom - domain is supported per storage account. This API can only be used to update one of tags, - accountType, or customDomain per call. To update multiple of these properties, call the API - multiple times with one change per call. This call does not change the storage keys for the - account. If you want to change storage account keys, use the RegenerateKey operation. The - location and name of the storage account cannot be changed after creation. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account within the specified resource group. - Storage account names must be between 3 and 24 characters in length and use numbers and - lower-case letters only. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword json: The parameters to update on the account. Note that only one property can be - changed at a time using this API. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json', - 'text/json'. Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-05-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}" # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), - "accountName": _SERIALIZER.url("account_name", account_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_keys_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - """Lists the access keys for the specified storage account. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-05-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/listKeys" # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), - "accountName": _SERIALIZER.url("account_name", account_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """Lists all the storage accounts available under the subscription. Note that storage keys are not - returned; use the ListKeys operation for this. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-05-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Storage/storageAccounts" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_list_by_resource_group_request(resource_group_name: str, subscription_id: str, **kwargs: Any) -> HttpRequest: - """Lists all the storage accounts available under the given resource group. Note that storage keys - are not returned; use the ListKeys operation for this. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-05-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = ( - "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts" - ) - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -@overload -def build_regenerate_key_request( - resource_group_name: str, - account_name: str, - subscription_id: str, - *, - json: JSON, - content_type: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - """Regenerates the access keys for the specified storage account. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account within the specified resource group. - Storage account names must be between 3 and 24 characters in length and use numbers and - lower-case letters only. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword json: Specifies name of the key which should be regenerated. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "keyName": "str" # Optional. Known values are: "key1" and "key2". - } - """ - - -@overload -def build_regenerate_key_request( - resource_group_name: str, - account_name: str, - subscription_id: str, - *, - content: IO, - content_type: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - """Regenerates the access keys for the specified storage account. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account within the specified resource group. - Storage account names must be between 3 and 24 characters in length and use numbers and - lower-case letters only. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword content: Specifies name of the key which should be regenerated. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'text/json'. Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_regenerate_key_request( - resource_group_name: str, account_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - """Regenerates the access keys for the specified storage account. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group within the user’s subscription. - Required. - :type resource_group_name: str - :param account_name: The name of the storage account within the specified resource group. - Storage account names must be between 3 and 24 characters in length and use numbers and - lower-case letters only. Required. - :type account_name: str - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :keyword json: Specifies name of the key which should be regenerated. Is either a model type or - a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json', - 'text/json'. Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-05-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Storage/storageAccounts/{accountName}/regenerateKey" # pylint: disable=line-too-long - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), - "accountName": _SERIALIZER.url("account_name", account_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/usage/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/usage/__init__.py deleted file mode 100644 index 1930355f8e5..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/usage/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_list_request - -__all__ = [ - "build_list_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/usage/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/usage/_request_builders.py deleted file mode 100644 index 2f332c3cbef..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/StorageManagementClientLowLevel/storagelowlevel/rest/usage/_request_builders.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_list_request(subscription_id: str, **kwargs: Any) -> HttpRequest: - """Gets the current usage count and the limit for the resources under the subscription. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param subscription_id: Gets subscription credentials which uniquely identify Microsoft Azure - subscription. The subscription ID forms part of the URI for every service call. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2015-05-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json, text/json") - - # Construct URL - _url = "/subscriptions/{subscriptionId}/providers/Microsoft.Storage/usages" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/setup.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/setup.py deleted file mode 100644 index 32f0b0c39a3..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "microsoftazuretesturl" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="MicrosoftAzureTestUrl", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-mgmt-core<2.0.0,>=1.3.0", - ], - long_description="""\ - Some cool documentation. - """, -) diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/__init__.py deleted file mode 100644 index 7db8e8a624b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import MicrosoftAzureTestUrl -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["MicrosoftAzureTestUrl"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_client.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_client.py deleted file mode 100644 index 0d7d1e7a1cc..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_client.py +++ /dev/null @@ -1,92 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core.rest import HttpRequest, HttpResponse -from azure.mgmt.core import ARMPipelineClient - -from ._configuration import MicrosoftAzureTestUrlConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials import TokenCredential - - -class MicrosoftAzureTestUrl: # pylint: disable=client-accepts-api-version-keyword - """Some cool documentation. - - :param subscription_id: Subscription Id. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - :keyword api_version: Api Version. Default value is "2014-04-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - subscription_id: str, - credential: "TokenCredential", - *, - endpoint: str = "http://localhost:3000", - **kwargs: Any - ) -> None: - self._config = MicrosoftAzureTestUrlConfiguration( - subscription_id=subscription_id, credential=credential, **kwargs - ) - self._client = ARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `subscriptionidapiversionlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from subscriptionidapiversionlowlevel.rest import group - >>> request = group.build_get_sample_resource_group_request(resource_group_name, subscription_id, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> MicrosoftAzureTestUrl - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_configuration.py deleted file mode 100644 index 7a115ac2582..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_configuration.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy - -from ._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import TokenCredential - - -class MicrosoftAzureTestUrlConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for MicrosoftAzureTestUrl. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param subscription_id: Subscription Id. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword api_version: Api Version. Default value is "2014-04-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, subscription_id: str, credential: "TokenCredential", **kwargs: Any) -> None: - super(MicrosoftAzureTestUrlConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2014-04-01-preview") # type: str - - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.subscription_id = subscription_id - self.credential = credential - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "microsoftazuretesturl/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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.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 - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_serialization.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_vendor.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_version.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/__init__.py deleted file mode 100644 index 99fcfa075d8..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import MicrosoftAzureTestUrl - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["MicrosoftAzureTestUrl"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_client.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_client.py deleted file mode 100644 index 3da3e01082b..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_client.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core.rest import AsyncHttpResponse, HttpRequest -from azure.mgmt.core import AsyncARMPipelineClient - -from .._serialization import Deserializer, Serializer -from ._configuration import MicrosoftAzureTestUrlConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials_async import AsyncTokenCredential - - -class MicrosoftAzureTestUrl: # pylint: disable=client-accepts-api-version-keyword - """Some cool documentation. - - :param subscription_id: Subscription Id. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - :keyword api_version: Api Version. Default value is "2014-04-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__( - self, - subscription_id: str, - credential: "AsyncTokenCredential", - *, - endpoint: str = "http://localhost:3000", - **kwargs: Any - ) -> None: - self._config = MicrosoftAzureTestUrlConfiguration( - subscription_id=subscription_id, credential=credential, **kwargs - ) - self._client = AsyncARMPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `subscriptionidapiversionlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from subscriptionidapiversionlowlevel.rest import group - >>> request = group.build_get_sample_resource_group_request(resource_group_name, subscription_id, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "MicrosoftAzureTestUrl": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_configuration.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_configuration.py deleted file mode 100644 index f53f24c492c..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_configuration.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies -from azure.mgmt.core.policies import ARMHttpLoggingPolicy, AsyncARMChallengeAuthenticationPolicy - -from .._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials_async import AsyncTokenCredential - - -class MicrosoftAzureTestUrlConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for MicrosoftAzureTestUrl. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param subscription_id: Subscription Id. Required. - :type subscription_id: str - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword api_version: Api Version. Default value is "2014-04-01-preview". Note that overriding - this default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, subscription_id: str, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(MicrosoftAzureTestUrlConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2014-04-01-preview") # type: str - - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.subscription_id = subscription_id - self.credential = credential - self.api_version = api_version - self.credential_scopes = kwargs.pop("credential_scopes", ["https://management.azure.com/.default"]) - kwargs.setdefault("sdk_moniker", "microsoftazuretesturl/{}".format(VERSION)) - 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") - if self.credential and not self.authentication_policy: - self.authentication_policy = AsyncARMChallengeAuthenticationPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_patch.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/py.typed b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/group/__init__.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/group/__init__.py deleted file mode 100644 index 3c1920b856c..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/group/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_sample_resource_group_request - -__all__ = [ - "build_get_sample_resource_group_request", -] diff --git a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/group/_request_builders.py b/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/group/_request_builders.py deleted file mode 100644 index 8b9e58a935a..00000000000 --- a/test/azure/low-level/Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel/subscriptionidapiversionlowlevel/rest/group/_request_builders.py +++ /dev/null @@ -1,59 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_sample_resource_group_request( - resource_group_name: str, subscription_id: str, **kwargs: Any -) -> HttpRequest: - """Provides a resouce group with name 'testgroup101' and location 'West US'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: Resource Group name 'testgroup101'. Required. - :type resource_group_name: str - :param subscription_id: Subscription Id. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("api-version", "2014-04-01-preview")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/azure/low-level/coverage/report-azure.json b/test/azure/low-level/coverage/report-azure.json deleted file mode 100644 index 07af3471cf1..00000000000 --- a/test/azure/low-level/coverage/report-azure.json +++ /dev/null @@ -1,143 +0,0 @@ -{ - "LROPostDoubleHeadersFinalLocationPost": 0, - "LROPostDoubleHeadersFinalLocationAsync": 0, - "LROPostDoubleHeadersFinalLocationGet": 0, - "LROConstantParameterizedPost": 0, - "LROConstantParameterizedGet": 0, - "PagingDuplicateParameters": 13, - "PostParameterGroupingWithReservedWords": 0, - "LROPutInlineComplete": 0, - "LROPutInlineComplete201": 0, - "CustomHeaderPutAsyncSucceded": 0, - "CustomHeaderPostAsyncSucceded": 0, - "CustomHeaderPutSucceeded": 0, - "CustomHeaderPostSucceeded": 0, - "LROPut200InlineCompleteNoState": 0, - "LROPatchInlineCompleteIgnoreHeaders": 0, - "LROPatch201WithAsyncHeader": 0, - "LROPatch202WithAsyncAndLocationHeader": 0, - "LROPut202Retry200": 0, - "LROPutSucceededWithBody": 0, - "LROPutSucceededNoBody": 0, - "LROPutFailed": 0, - "LROPutCanceled": 0, - "LROPutAsyncRetrySucceeded": 0, - "LROPutAsyncNoRetrySucceeded": 0, - "LROPutAsyncRetryFailed": 0, - "LROPutAsyncNoRetryCanceled": 0, - "LROPutNoHeaderInRetry": 0, - "LROPutAsyncNoHeaderInRetry": 0, - "LRODeleteNoHeaderInRetry": 0, - "LRODeleteAsyncNoHeaderInRetry": 0, - "LROPutSubResourceInRetry": 0, - "LROPutSubResourceAsyncInRetry": 0, - "LROPutNonResourceInRetry": 0, - "LROPutNonResourceAsyncInRetry": 0, - "LRODeleteProvisioningSucceededWithBody": 0, - "LRODeleteProvisioningFailed": 0, - "LRODeleteProvisioningCanceled": 0, - "LRODeleteInlineComplete": 0, - "LRODelete200": 0, - "LRODelete204": 0, - "LRODeleteAsyncRetrySucceeded": 0, - "LRODeleteAsyncNoRetrySucceeded": 0, - "LRODeleteAsyncRetryFailed": 0, - "LRODeleteAsyncRetryCanceled": 0, - "LROPostSuccededWithBody": 0, - "LROPostSuccededNoBody": 0, - "LROPost200": 0, - "LROPostDoubleHeadersFinalAzureHeaderGet": 0, - "LROPostDoubleHeadersFinalAzureHeaderGetDefault": 0, - "LROPostAndGetList": 0, - "LROPostAsyncRetrySucceeded": 0, - "LROPostAsyncNoRetrySucceeded": 0, - "LROPostAsyncRetryFailed": 0, - "LROPostAsyncRetryCanceled": 0, - "LRORetryPutSucceededWithBody": 0, - "LRORetryErrorPutAsyncSucceeded": 0, - "LRORetryErrorPutAsyncSucceededPolling": 0, - "LRORetryErrorDelete202Accepted200Succeeded": 0, - "LRORetryErrorDelete202Retry200Succeeded": 0, - "LRORetryErrorDeleteAsyncRetrySucceeded": 0, - "LRORetryErrorPost202Retry200Succeeded": 0, - "LRORetryErrorPostAsyncRetrySucceeded": 0, - "LRONonRetryPut400": 0, - "LRONonRetryPut201Creating400": 0, - "LRONonRetryPut201Creating400InvalidJson": 0, - "LRONonRetryPutAsyncRetry400": 0, - "LRONonRetryDelete400": 0, - "LRONonRetryDelete202Retry400": 0, - "LRONonRetryDeleteAsyncRetry400": 0, - "LRONonRetryPost400": 0, - "LRONonRetryPost202Retry400": 0, - "LRONonRetryPostAsyncRetry400": 0, - "LROErrorPut201NoProvisioningStatePayload": 0, - "LROErrorPutAsyncNoPollingStatus": 0, - "LROErrorPutAsyncNoPollingStatusPayload": 0, - "LROErrorPut200InvalidJson": 0, - "LROErrorPutAsyncInvalidHeader": 0, - "LROErrorPutAsyncInvalidJsonPolling": 0, - "LROErrorDeleteNoLocation": 0, - "LROErrorDelete202RetryInvalidHeader": 0, - "LROErrorDeleteAsyncNoPollingStatus": 0, - "LROErrorDeleteAsyncInvalidHeader": 0, - "LROErrorDeleteAsyncInvalidJsonPolling": 0, - "LROErrorPostNoLocation": 0, - "LROErrorPost202RetryInvalidHeader": 0, - "LROErrorPostAsyncNoPollingPayload": 0, - "LROErrorPostAsyncInvalidHeader": 0, - "LROErrorPostAsyncInvalidJsonPolling": 0, - "LROParameterizedEndpoint": 0, - "PagingNoItemName": 6, - "PagingNextLinkNameNull": 6, - "PagingSingle": 10, - "PagingMultiple": 10, - "PagingMultipleWithQueryParameters": 6, - "PagingOdataMultiple": 6, - "PagingMultiplePath": 6, - "PagingMultipleRetryFirst": 6, - "PagingMultipleRetrySecond": 6, - "PagingSingleFailure": 6, - "PagingMultipleFailure": 6, - "PagingMultipleFailureUri": 6, - "PagingFragment": 6, - "PagingMultipleLRO": 4, - "PagingCustomUrlPartialNextLink": 8, - "PagingCustomUrlPartialOperationNextLink": 8, - "PagingReturnModelWithXMSClientName": 4, - "PagingFirstResponseEmpty": 6, - "AzureSubscriptionMethodLocalValid": 0, - "AzureSubscriptionMethodGlobalValid": 0, - "AzureSubscriptionMethodGlobalNotProvidedValid": 0, - "AzureSubscriptionPathLocalValid": 0, - "AzureSubscriptionPathGlobalValid": 0, - "AzureSubscriptionSwaggerLocalValid": 0, - "AzureSubscriptionSwaggerGlobalValid": 0, - "AzureApiVersionMethodLocalNull": 0, - "AzureApiVersionMethodLocalValid": 0, - "AzureApiVersionMethodGlobalValid": 0, - "AzureApiVersionMethodGlobalNotProvidedValid": 0, - "AzureApiVersionPathLocalValid": 0, - "AzureApiVersionPathGlobalValid": 0, - "AzureApiVersionSwaggerLocalValid": 0, - "AzureApiVersionSwaggerGlobalValid": 0, - "AzureMethodPathUrlEncoding": 0, - "AzurePathPathUrlEncoding": 0, - "AzureSwaggerPathUrlEncoding": 0, - "AzureMethodQueryUrlEncoding": 0, - "AzurePathQueryUrlEncoding": 0, - "AzureSwaggerQueryUrlEncoding": 0, - "AzureMethodQueryUrlEncodingNull": 0, - "AzureXmsRequestClientOverwrite": 0, - "AzureXmsRequestClientOverwriteViaParameter": 0, - "AzureXmsRequestClientIdNull": 0, - "AzureXmsCustomNamedRequestId": 0, - "AzureXmsCustomNamedRequestIdParameterGroup": 0, - "AzureRequestClientIdInError": 0, - "AzureODataFilter": 0, - "SubscriptionIdAndApiVersion": 0, - "postParameterGroupingOptionalParameters": 0, - "postParameterGroupingRequiredParameters": 0, - "postParameterGroupingMultipleParameterGroups": 0, - "postParameterGroupingSharedParameterGroupObject": 0 -} \ No newline at end of file diff --git a/test/azure/low-level/coverage/report-dpg.json b/test/azure/low-level/coverage/report-dpg.json deleted file mode 100644 index d2e2590c4b1..00000000000 --- a/test/azure/low-level/coverage/report-dpg.json +++ /dev/null @@ -1,16 +0,0 @@ -{ - "GetRawModel": 0, - "GetHandwrittenModel": 0, - "PostRawModel": 0, - "PostHandwrittenModel": 0, - "GetRawPages": 0, - "GetHandwrittenModelPages": 0, - "RawLRO": 0, - "HandwrittenModelLRO": 0, - "DPGAddOptionalInput": 8, - "DPGNewBodyType.JSON": 0, - "DPGNewBodyType.JPEG": 0, - "DPGNewBodyType": 0, - "DPGAddNewOperation": 0, - "DPGAddNewPath": 0 -} \ No newline at end of file diff --git a/test/azure/low-level/coverage/report-optional.json b/test/azure/low-level/coverage/report-optional.json deleted file mode 100644 index 56ad3b2c633..00000000000 --- a/test/azure/low-level/coverage/report-optional.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "StreamUploadFile": 54, - "UpdatePetWithForm": 0, - "UrlEncodedDataWithPartialConstantBody": 0, - "getDecimalInvalid": 10, - "getDecimalBig": 10, - "getDecimalSmall": 10, - "getDecimalBigPositiveDecimal": 10, - "getDecimalBigNegativeDecimal": 10, - "putDecimalBig": 10, - "putDecimalSmall": 10, - "putDecimalBigPositiveDecimal": 10, - "putDecimalBigNegativeDecimal": 6, - "putDateTimeMaxUtc7MS": 0, - "getDateTimeMaxUtc7MSUppercase": 12, - "putDateTimeMaxLocalPositiveOffset": 12, - "putDateTimeMaxLocalNegativeOffset": 0, - "putDateTimeMinLocalPositiveOffset": 0, - "putDateTimeMinLocalNegativeOffset": 12, - "HeaderParameterProtectedKey": 1, - "CustomHeaderInRequest": 11, - "FormdataStreamUploadFile": 36, - "HttpSuccess200Options": 0, - "HttpRedirect307Options": 0, - "HttpRetry502Options": 0, - "HttpClientFailure400Options": 0, - "HttpClientFailure403Options": 0, - "HttpClientFailure412Options": 0, - "ResponsesScenarioNoModelEmptyBody": 10, - "sendErrorWithParamNameModels": 24, - "MultiapiPutTestOneApiVersionOne": 0, - "MultiapiPutTestOneApiVersionTwo": 0, - "MultiapiGetTestTwoApiVersionOne": 0, - "MultiapiGetTestTwoApiVersionTwo": 0, - "MultiapiGetTestTwoApiVersionThree": 0, - "MultiapiPutTestThreeApiVersionTwo": 0, - "MultiapiPostTestFourApiVersionTwo": 0, - "MultiapiPostTestFourApiVersionThreeJSON": 0, - "MultiapiPostTestFourApiVersionThreePDF": 0, - "MultiapiPutTestFiveApiVersionThree": 0, - "MultiapiLRO": 0, - "MultiapiPaging": 0, - "MultiapiLROAndPaging": 0, - "MultiapiDifferentCallsApiVersionOne": 0, - "MultiapiDifferentCallsApiVersionTwo": 0, - "MultiapiDifferentCallsApiVersionThree": 0, - "MultiapiCustomBaseUrlApiVersionOne": 0, - "MultiapiCustomBaseUrlApiVersionTwo": 0, - "LROPatchInlineCompleteIgnoreHeaders": 0 -} \ No newline at end of file diff --git a/test/azure/low-level/coverage/report-vanilla.json b/test/azure/low-level/coverage/report-vanilla.json deleted file mode 100644 index aa5a9b2a944..00000000000 --- a/test/azure/low-level/coverage/report-vanilla.json +++ /dev/null @@ -1,637 +0,0 @@ -{ - "additionalPropertiesTrue": 13, - "additionalPropertiesSubclass": 13, - "additionalPropertiesTypeObject": 13, - "additionalPropertiesTypeString": 13, - "additionalPropertiesInProperties": 13, - "additionalPropertiesInPropertiesWithAPTypeString": 13, - "GetStringAsAnything": 13, - "PutStringAsAnything": 13, - "GetObjectAsAnything": 13, - "PutObjectAsAnything": 13, - "GetArrayAsAnything": 13, - "PutArrayAsAnything": 13, - "putArrayEmpty": 14, - "getArrayEmpty": 14, - "getArrayNull": 14, - "getArrayInvalid": 14, - "getArrayBooleanValid": 14, - "putArrayBooleanValid": 14, - "getArrayBooleanWithNull": 14, - "getArrayBooleanWithString": 14, - "getArrayIntegerValid": 14, - "putArrayIntegerValid": 14, - "getArrayIntegerWithNull": 14, - "getArrayIntegerWithString": 14, - "getArrayLongValid": 14, - "putArrayLongValid": 14, - "getArrayLongWithNull": 14, - "getArrayLongWithString": 14, - "getArrayFloatValid": 14, - "putArrayFloatValid": 14, - "getArrayFloatWithNull": 14, - "getArrayFloatWithString": 14, - "getArrayDoubleValid": 14, - "putArrayDoubleValid": 14, - "getArrayDoubleWithNull": 14, - "getArrayDoubleWithString": 14, - "getArrayStringValid": 14, - "putArrayStringValid": 14, - "getArrayStringWithNull": 14, - "getArrayStringWithNumber": 27, - "getArrayEnumValid": 13, - "putArrayEnumValid": 13, - "getArrayStringEnumValid": 13, - "putArrayStringEnumValid": 13, - "getArrayUuidValid": 14, - "putArrayUuidValid": 14, - "getArrayUuidWithInvalidChars": 14, - "getArrayDateValid": 14, - "putArrayDateValid": 14, - "getArrayDateWithNull": 13, - "getArrayDateWithInvalidChars": 13, - "getArrayDateTimeValid": 14, - "putArrayDateTimeValid": 14, - "getArrayDateTimeWithNull": 13, - "getArrayDateTimeWithInvalidChars": 13, - "getArrayDateTimeRfc1123Valid": 14, - "getDateTimeRfc1123Valid": 0, - "getArrayDurationValid": 14, - "putArrayDurationValid": 14, - "getArrayByteValid": 14, - "putArrayByteValid": 14, - "getArrayByteWithNull": 14, - "getArrayBase64Url": 19, - "getArrayComplexNull": 14, - "getArrayComplexEmpty": 14, - "getArrayComplexItemNull": 14, - "getArrayComplexItemEmpty": 14, - "getArrayComplexValid": 14, - "putArrayComplexValid": 14, - "getArrayArrayNull": 14, - "getArrayArrayEmpty": 14, - "getArrayArrayItemNull": 14, - "getArrayArrayItemEmpty": 14, - "getArrayArrayValid": 14, - "putArrayArrayValid": 14, - "getArrayDictionaryNull": 14, - "getArrayDictionaryEmpty": 14, - "getArrayDictionaryItemNull": 14, - "getArrayDictionaryItemEmpty": 14, - "getArrayDictionaryValid": 14, - "putArrayDictionaryValid": 14, - "BodyBinaryFile": 0, - "BodyBinaryOctet": 0, - "getBoolTrue": 12, - "putBoolTrue": 12, - "getBoolFalse": 12, - "putBoolFalse": 12, - "getBoolNull": 12, - "getBoolInvalid": 12, - "putByteNonAscii": 12, - "getByteNull": 12, - "getByteEmpty": 12, - "getByteNonAscii": 12, - "getByteInvalid": 12, - "ConstantClientProperties": 12, - "ErrorWithSecrets": 0, - "RequestWithSecrets": 0, - "HttpSuccess200Head": 44, - "HttpSuccess200Get": 10, - "HttpSuccess200Put": 10, - "HttpSuccess200Post": 10, - "HttpSuccess200Patch": 10, - "HttpSuccess200Delete": 10, - "HttpSuccess201Put": 10, - "HttpSuccess201Post": 10, - "HttpSuccess202Put": 10, - "HttpSuccess202Post": 10, - "HttpSuccess202Patch": 10, - "HttpSuccess202Delete": 10, - "HttpSuccess204Head": 44, - "HttpSuccess204Put": 10, - "HttpSuccess204Post": 10, - "HttpSuccess204Patch": 10, - "HttpSuccess204Delete": 10, - "HttpSuccess404Head": 44, - "HttpRedirect300Head": 10, - "HttpRedirect300Get": 10, - "HttpRedirect301Head": 0, - "HttpRedirect301Put": 10, - "HttpRedirect301Get": 10, - "HttpRedirect302Head": 10, - "HttpRedirect302Get": 10, - "HttpRedirect302Patch": 10, - "HttpRedirect303Post": 10, - "HttpRedirect307Head": 10, - "HttpRedirect307Get": 10, - "HttpRedirect307Put": 10, - "HttpRedirect307Post": 10, - "HttpRedirect307Patch": 10, - "HttpRedirect307Delete": 10, - "HttpRedirect307Options": 0, - "HttpClientFailure400Head": 11, - "HttpClientFailure400Get": 11, - "HttpClientFailure400Put": 11, - "HttpClientFailure400Post": 11, - "HttpClientFailure400Patch": 11, - "HttpClientFailure400Delete": 11, - "HttpClientFailure401Head": 11, - "HttpClientFailure402Get": 11, - "HttpClientFailure403Get": 11, - "HttpClientFailure404Put": 11, - "HttpClientFailure405Patch": 11, - "HttpClientFailure406Post": 11, - "HttpClientFailure407Delete": 11, - "HttpClientFailure409Put": 11, - "HttpClientFailure410Head": 11, - "HttpClientFailure411Get": 11, - "HttpClientFailure412Get": 11, - "HttpClientFailure413Put": 11, - "HttpClientFailure414Patch": 11, - "HttpClientFailure415Post": 11, - "HttpClientFailure416Get": 11, - "HttpClientFailure417Delete": 11, - "HttpClientFailure429Head": 43, - "HttpServerFailure501Head": 11, - "HttpServerFailure501Get": 11, - "HttpServerFailure505Post": 11, - "HttpServerFailure505Delete": 11, - "HttpRetry408Head": 11, - "HttpRetry500Put": 11, - "HttpRetry500Patch": 11, - "HttpRetry502Get": 11, - "HttpRetry503Post": 11, - "HttpRetry503Delete": 11, - "HttpRetry504Put": 11, - "HttpRetry504Patch": 11, - "ResponsesScenarioA200MatchingModel": 11, - "ResponsesScenarioA201DefaultNoModel": 11, - "ResponsesScenarioA202DefaultNoModel": 11, - "ResponsesScenarioA204MatchingNoModel": 11, - "ResponsesScenarioA400DefaultModel": 11, - "ResponsesScenarioB200MatchingModel": 11, - "ResponsesScenarioB201MatchingModel": 11, - "ResponsesScenarioB400DefaultModel": 11, - "ResponsesScenarioC200MatchingModel": 11, - "ResponsesScenarioC201MatchingModel": 11, - "ResponsesScenarioC404MatchingModel": 11, - "ResponsesScenarioC400DefaultModel": 11, - "ResponsesScenarioD202MatchingNoModel": 11, - "ResponsesScenarioD204MatchingNoModel": 11, - "ResponsesScenarioD400DefaultModel": 11, - "ResponsesScenarioE202MatchingInvalid": 11, - "ResponsesScenarioE204MatchingNoModel": 11, - "ResponsesScenarioE400DefaultNoModel": 11, - "ResponsesScenarioE400DefaultInvalid": 11, - "ResponsesScenarioF200DefaultModel": 22, - "ResponsesScenarioF200DefaultNone": 22, - "ResponsesScenarioF400DefaultModel": 5, - "ResponsesScenarioF400DefaultNone": 5, - "ResponsesScenarioG200DefaultInvalid": 15, - "ResponsesScenarioG200DefaultNoModel": 7, - "ResponsesScenarioG400DefaultInvalid": 11, - "ResponsesScenarioG400DefaultNoModel": 11, - "ResponsesScenarioH200MatchingNone": 11, - "ResponsesScenarioH200MatchingModel": 11, - "ResponsesScenarioH200MatchingInvalid": 11, - "ResponsesScenarioH400NonMatchingNone": 11, - "ResponsesScenarioH400NonMatchingModel": 11, - "ResponsesScenarioH400NonMatchingInvalid": 11, - "ResponsesScenarioH202NonMatchingModel": 11, - "ResponsesScenarioEmptyErrorBody": 10, - "ResponsesScenarioNoModelErrorBody": 10, - "ResponsesScenarioNoModelEmptyBody": 0, - "verifyIncorrectErrorParsing": 4, - "MediaTypesAnalyzeBodyNoAcceptHeader": 20, - "MediaTypesTwoContentTypes": 0, - "MediaTypesThreeContentTypes": 0, - "PassMergePatchObject": 0, - "GetParameterizedHostWithNameEndpoint": 10, - "UrlPathsBoolTrue": 10, - "UrlPathsBoolFalse": 10, - "UrlPathsIntPositive": 10, - "UrlPathsIntUnixTime": 10, - "UrlPathsIntNegative": 10, - "UrlPathsLongPositive": 10, - "UrlPathsLongNegative": 10, - "UrlPathsFloatPositive": 10, - "UrlPathsFloatNegative": 10, - "UrlPathsDoublePositive": 10, - "UrlPathsDoubleNegative": 10, - "UrlPathsStringEmpty": 10, - "UrlPathsStringUnicode": 10, - "UrlPathsStringUrlEncoded": 10, - "UrlPathsStringUrlNonEncoded": 10, - "UrlPathsStringBase64Url": 10, - "UrlPathsByteEmpty": 10, - "UrlPathsByteMultiByte": 10, - "UrlPathsDateValid": 10, - "UrlPathsDateTimeValid": 10, - "UrlPathsEnumValid": 10, - "UrlPathsArrayCSVInPath": 10, - "ImplicitOptionalBinaryBody": 6, - "ExplicitOptionalBinaryBody": 14, - "ExplicitRequiredBinaryBody": 8, - "OptionalImplicitBody": 10, - "GeneralOptional": 110, - "OptionalImplicitHeader": 10, - "OptionalImplicitQuery": 10, - "OptionalGlobalQuery": 10, - "reservedWordsOperationGroupImport": 10, - "reservedWordsBodyNamedContent": 0, - "reservedWordsBodyNamedJson": 0, - "reservedWordsBodyNamedData": 0, - "reservedWordsBodyNamedFiles": 0, - "reservedWordsUrlHeaderQuery": 0, - "SecurityKey": 0, - "SecurityAad": 0, - "getStringNull": 10, - "putStringNull": 10, - "getStringEmpty": 10, - "putStringEmpty": 10, - "getStringNotProvided": 10, - "getStringWithLeadingAndTrailingWhitespace": 10, - "putStringWithLeadingAndTrailingWhitespace": 10, - "getStringBase64UrlEncoded": 10, - "putStringBase64UrlEncoded": 10, - "getStringBase64Encoded": 10, - "getStringNullBase64UrlEncoding": 10, - "getStringMultiByteCharacters": 10, - "putStringMultiByteCharacters": 10, - "getEnumNotExpandable": 10, - "putEnumNotExpandable": 18, - "getEnumReferenced": 10, - "putEnumReferenced": 22, - "getEnumReferencedConstant": 10, - "putEnumReferencedConstant": 6, - "XmlGetBytes": 10, - "XmlPutBytes": 10, - "XmlGetUrl": 10, - "XmlPutUrl": 10, - "putArrayDateTimeRfc1123Valid": 14, - "getDateNull": 12, - "getDateInvalid": 12, - "getDateOverflow": 12, - "getDateUnderflow": 12, - "getDateMax": 12, - "putDateMax": 12, - "getDateMin": 12, - "putDateMin": 12, - "getDateTimeNull": 12, - "getDateTimeInvalid": 12, - "getDateTimeOverflow": 12, - "getDateTimeUnderflow": 12, - "putDateTimeMaxUtc": 12, - "getDateTimeMaxUtcLowercase": 12, - "getDateTimeMaxUtcUppercase": 12, - "getDateTimeMaxLocalPositiveOffsetLowercase": 12, - "getDateTimeMaxLocalPositiveOffsetUppercase": 12, - "getDateTimeMaxLocalNegativeOffsetLowercase": 12, - "getDateTimeMaxLocalNegativeOffsetUppercase": 12, - "getDateTimeMinUtc": 12, - "putDateTimeMinUtc": 12, - "getDateTimeMinLocalPositiveOffset": 12, - "getDateTimeMinLocalNegativeOffset": 12, - "getDateTimeRfc1123Null": 12, - "getDateTimeRfc1123Invalid": 12, - "getDateTimeRfc1123Overflow": 12, - "getDateTimeRfc1123Underflow": 12, - "getDateTimeRfc1123MinUtc": 12, - "putDateTimeRfc1123Max": 12, - "putDateTimeRfc1123Min": 12, - "getDateTimeRfc1123MaxUtcLowercase": 12, - "getDateTimeRfc1123MaxUtcUppercase": 12, - "getIntegerNull": 12, - "getIntegerInvalid": 10, - "getIntegerOverflow": 11, - "getIntegerUnderflow": 11, - "getLongOverflow": 11, - "getLongUnderflow": 11, - "putIntegerMax": 11, - "putLongMax": 11, - "putIntegerMin": 11, - "putLongMin": 11, - "getNumberNull": 10, - "getFloatInvalid": 10, - "getDoubleInvalid": 10, - "getFloatBigScientificNotation": 10, - "putFloatBigScientificNotation": 10, - "getDoubleBigScientificNotation": 10, - "putDoubleBigScientificNotation": 10, - "getDoubleBigPositiveDecimal": 10, - "putDoubleBigPositiveDecimal": 10, - "getDoubleBigNegativeDecimal": 10, - "putDoubleBigNegativeDecimal": 10, - "getFloatSmallScientificNotation": 10, - "putFloatSmallScientificNotation": 10, - "getDoubleSmallScientificNotation": 10, - "putDoubleSmallScientificNotation": 10, - "putComplexBasicValid": 22, - "getComplexBasicValid": 12, - "getComplexBasicEmpty": 12, - "getComplexBasicNotProvided": 12, - "getComplexBasicNull": 12, - "getComplexBasicInvalid": 12, - "putComplexPrimitiveInteger": 12, - "putComplexPrimitiveLong": 12, - "putComplexPrimitiveFloat": 12, - "putComplexPrimitiveDouble": 12, - "putComplexPrimitiveBool": 12, - "putComplexPrimitiveString": 12, - "putComplexPrimitiveDate": 12, - "putComplexPrimitiveDateTime": 12, - "putComplexPrimitiveDateTimeRfc1123": 12, - "putComplexPrimitiveDuration": 12, - "putComplexPrimitiveByte": 12, - "getComplexPrimitiveInteger": 12, - "getComplexPrimitiveLong": 12, - "getComplexPrimitiveFloat": 12, - "getComplexPrimitiveDouble": 12, - "getComplexPrimitiveBool": 12, - "getComplexPrimitiveString": 12, - "getComplexPrimitiveDate": 12, - "getComplexPrimitiveDateTime": 12, - "getComplexPrimitiveDateTimeRfc1123": 12, - "getComplexPrimitiveDuration": 12, - "getComplexPrimitiveByte": 12, - "putComplexArrayValid": 12, - "putComplexArrayEmpty": 12, - "getComplexArrayValid": 12, - "getComplexArrayEmpty": 12, - "getComplexArrayNotProvided": 12, - "putComplexDictionaryValid": 12, - "putComplexDictionaryEmpty": 12, - "getComplexDictionaryValid": 12, - "getComplexDictionaryEmpty": 12, - "getComplexDictionaryNull": 12, - "getComplexDictionaryNotProvided": 12, - "putComplexInheritanceValid": 26, - "getComplexInheritanceValid": 42, - "putComplexPolymorphismValid": 12, - "getComplexPolymorphismValid": 12, - "putComplexPolymorphismComplicated": 12, - "getComplexPolymorphismComplicated": 12, - "putComplexPolymorphismNoDiscriminator": 12, - "putComplexPolymorphicRecursiveValid": 12, - "getComplexPolymorphicRecursiveValid": 12, - "putComplexReadOnlyPropertyValid": 12, - "getComplexReadOnlyPropertyValid": 12, - "UrlQueriesBoolFalse": 10, - "UrlQueriesBoolTrue": 10, - "UrlQueriesBoolNull": 10, - "UrlQueriesIntPositive": 10, - "UrlQueriesIntNegative": 10, - "UrlQueriesIntNull": 10, - "UrlQueriesLongPositive": 10, - "UrlQueriesLongNegative": 10, - "UrlQueriesLongNull": 10, - "UrlQueriesFloatPositive": 10, - "UrlQueriesFloatNegative": 10, - "UrlQueriesFloatNull": 10, - "UrlQueriesDoublePositive": 10, - "UrlQueriesDoubleNegative": 10, - "UrlQueriesDoubleNull": 10, - "UrlQueriesStringUrlEncoded": 10, - "UrlQueriesStringEmpty": 10, - "UrlQueriesStringNull": 10, - "UrlQueriesStringUnicode": 10, - "UrlQueriesEnumValid": 10, - "UrlQueriesEnumNull": 10, - "UrlQueriesByteMultiByte": 10, - "UrlQueriesByteEmpty": 10, - "UrlQueriesByteNull": 10, - "UrlQueriesDateValid": 10, - "UrlQueriesDateNull": 10, - "UrlQueriesDateTimeValid": 10, - "UrlQueriesDateTimeNull": 10, - "UrlQueriesArrayCsvNull": 10, - "UrlQueriesArrayCsvEmpty": 10, - "UrlQueriesArrayCsvValid": 10, - "UrlQueriesArrayMultiNull": 10, - "UrlQueriesArrayMultiEmpty": 10, - "UrlQueriesArrayMultiValid": 10, - "UrlQueriesArraySsvValid": 10, - "UrlQueriesArrayPipesValid": 10, - "UrlQueriesArrayTsvValid": 5, - "UrlQueriesArrayNoCollectionFormatValid": 10, - "UrlPathItemGetAll": 10, - "UrlPathItemGetGlobalNull": 10, - "UrlPathItemGetGlobalAndLocalNull": 10, - "UrlPathItemGetPathItemAndLocalNull": 10, - "putDictionaryEmpty": 12, - "getDictionaryNull": 12, - "getDictionaryEmpty": 12, - "getDictionaryInvalid": 12, - "getDictionaryNullValue": 11, - "getDictionaryNullkey": 12, - "getDictionaryKeyEmptyString": 12, - "getDictionaryBooleanValid": 12, - "getDictionaryBooleanWithNull": 12, - "getDictionaryBooleanWithString": 12, - "getDictionaryIntegerValid": 12, - "getDictionaryIntegerWithNull": 12, - "getDictionaryIntegerWithString": 12, - "getDictionaryLongValid": 12, - "getDictionaryLongWithNull": 12, - "getDictionaryLongWithString": 12, - "getDictionaryFloatValid": 12, - "getDictionaryFloatWithNull": 12, - "getDictionaryFloatWithString": 12, - "getDictionaryDoubleValid": 12, - "getDictionaryDoubleWithNull": 12, - "getDictionaryDoubleWithString": 12, - "getDictionaryStringValid": 12, - "getDictionaryStringWithNull": 12, - "getDictionaryStringWithNumber": 12, - "getDictionaryDateValid": 12, - "getDictionaryDateWithNull": 12, - "getDictionaryDateWithInvalidChars": 12, - "getDictionaryDateTimeValid": 12, - "getDictionaryDateTimeWithNull": 12, - "getDictionaryDateTimeWithInvalidChars": 12, - "getDictionaryDateTimeRfc1123Valid": 12, - "getDictionaryDurationValid": 12, - "getDictionaryByteValid": 12, - "getDictionaryByteWithNull": 12, - "putDictionaryBooleanValid": 12, - "putDictionaryIntegerValid": 12, - "putDictionaryLongValid": 12, - "putDictionaryFloatValid": 12, - "putDictionaryDoubleValid": 12, - "putDictionaryStringValid": 12, - "putDictionaryDateValid": 12, - "putDictionaryDateTimeValid": 12, - "putDictionaryDateTimeRfc1123Valid": 12, - "putDictionaryDurationValid": 12, - "putDictionaryByteValid": 12, - "getDictionaryComplexNull": 12, - "getDictionaryComplexEmpty": 12, - "getDictionaryComplexItemNull": 12, - "getDictionaryComplexItemEmpty": 12, - "getDictionaryComplexValid": 12, - "putDictionaryComplexValid": 12, - "getDictionaryArrayNull": 12, - "getDictionaryArrayEmpty": 12, - "getDictionaryArrayItemNull": 12, - "getDictionaryArrayItemEmpty": 12, - "getDictionaryArrayValid": 12, - "putDictionaryArrayValid": 12, - "getDictionaryDictionaryNull": 12, - "getDictionaryDictionaryEmpty": 12, - "getDictionaryDictionaryItemNull": 12, - "getDictionaryDictionaryItemEmpty": 12, - "getDictionaryDictionaryValid": 12, - "putDictionaryDictionaryValid": 12, - "putDurationPositive": 29, - "getDurationNull": 29, - "getDurationInvalid": 29, - "getDurationPositive": 29, - "HeaderParameterExistingKey": 11, - "HeaderResponseExistingKey": 11, - "HeaderResponseProtectedKey": 11, - "HeaderParameterIntegerPositive": 11, - "HeaderParameterIntegerNegative": 11, - "HeaderParameterLongPositive": 11, - "HeaderParameterLongNegative": 11, - "HeaderParameterFloatPositive": 11, - "HeaderParameterFloatNegative": 11, - "HeaderParameterDoublePositive": 11, - "HeaderParameterDoubleNegative": 11, - "HeaderParameterBoolTrue": 11, - "HeaderParameterBoolFalse": 11, - "HeaderParameterStringValid": 11, - "HeaderParameterStringNull": 11, - "HeaderParameterStringEmpty": 11, - "HeaderParameterDateValid": 11, - "HeaderParameterDateMin": 11, - "HeaderParameterDateTimeValid": 11, - "HeaderParameterDateTimeMin": 11, - "HeaderParameterDateTimeRfc1123Valid": 11, - "HeaderParameterDateTimeRfc1123Min": 11, - "HeaderParameterBytesValid": 11, - "HeaderParameterDurationValid": 11, - "HeaderResponseIntegerPositive": 11, - "HeaderResponseIntegerNegative": 11, - "HeaderResponseLongPositive": 11, - "HeaderResponseLongNegative": 11, - "HeaderResponseFloatPositive": 11, - "HeaderResponseFloatNegative": 11, - "HeaderResponseDoublePositive": 11, - "HeaderResponseDoubleNegative": 11, - "HeaderResponseBoolTrue": 11, - "HeaderResponseBoolFalse": 11, - "HeaderResponseStringValid": 11, - "HeaderResponseStringNull": 11, - "HeaderResponseStringEmpty": 11, - "HeaderParameterEnumValid": 20, - "HeaderParameterEnumNull": 11, - "HeaderResponseEnumValid": 11, - "HeaderResponseEnumNull": 11, - "HeaderResponseDateValid": 11, - "HeaderResponseDateMin": 11, - "HeaderResponseDateTimeValid": 11, - "HeaderResponseDateTimeMin": 11, - "HeaderResponseDateTimeRfc1123Valid": 11, - "HeaderResponseDateTimeRfc1123Min": 11, - "HeaderResponseBytesValid": 11, - "HeaderResponseDurationValid": 11, - "ConstantsInPath": 10, - "ConstantsInBody": 10, - "CustomBaseUri": 11, - "CustomBaseUriMoreOptions": 7, - "getModelFlattenArray": 10, - "putModelFlattenArray": 10, - "getModelFlattenDictionary": 10, - "putModelFlattenDictionary": 10, - "getModelFlattenResourceCollection": 10, - "putModelFlattenResourceCollection": 10, - "putModelFlattenCustomBase": 10, - "postModelFlattenCustomParameter": 10, - "putModelFlattenCustomGroupedParameter": 10, - "getDictionaryBase64Url": 12, - "getUnixTime": 11, - "getInvalidUnixTime": 10, - "getNullUnixTime": 12, - "putUnixTime": 11, - "expectedEnum": 12, - "unexpectedEnum": 12, - "allowedValueEnum": 12, - "roundTripEnum": 12, - "expectedNoErrors": 12, - "expectedPetSadError": 59, - "expectedPetHungryError": 6, - "intError": 6, - "stringError": 6, - "animalNotFoundError": 6, - "linkNotFoundError": 6, - "getDateTimeMinLocalNoOffset": 12, - "getComplexPolymorphismDotSyntax": 12, - "getComposedWithDiscriminator": 12, - "getComposedWithoutDiscriminator": 12, - "FileStreamNonempty": 30, - "FileStreamVeryLarge": 13, - "FileStreamEmpty": 20, - "MediaTypeJson": 10, - "MediaTypePdf": 10, - "MediaTypeWithEncoding": 10, - "StorageListContainersXML": 10, - "StorageGetServicePropertiesXML": 10, - "StoragePutServicePropertiesXML": 10, - "StorageGetContainerACLXML": 10, - "StorageListBlobsXML": 10, - "StoragePutContainerACLXML": 10, - "GetSimpleXML": 10, - "PutSimpleXML": 10, - "GetWrappedXMLList": 10, - "PutWrappedXMLList": 10, - "GetEmptyXMLList": 10, - "PutEmptyXMLList": 10, - "GetEmptyWrappedXMLList": 10, - "PutEmptyWrappedXMLList": 10, - "GetXMLListAtRoot": 10, - "PutXMLListAtRoot": 10, - "GetXMLListAtRootSingle": 10, - "PutXMLListAtRootSingle": 10, - "GetEmptyXMLListAtRoot": 14, - "PutEmptyXMLListAtRoot": 10, - "GetXMLEmptyNode": 10, - "PutXMLEmptyNode": 10, - "GetRootWithRefAndNoMetaXML": 10, - "PutRootWithRefAndNoMetaXML": 10, - "GetRootWithRefAndMetaXML": 10, - "PutRootWithRefAndMetaXML": 10, - "jsonInputInXMLSwagger": 10, - "jsonOutputInXMLSwagger": 10, - "GetWithXMsText": 10, - "ObjectTypeResponse": 10, - "ObjectTypePut": 10, - "ObjectTypeErrorResponse": 10, - "NonStringEnumsPostInt": 10, - "NonStringEnumsGetInt": 10, - "NonStringEnumsPostFloat": 10, - "NonStringEnumsGetFloat": 10, - "BodyTimeGet": 10, - "BodyTimePut": 10, - "MultipleInheritancePetGet": 10, - "MultipleInheritancePetPut": 10, - "MultipleInheritanceHorseGet": 10, - "MultipleInheritanceHorsePut": 10, - "MultipleInheritanceFelineGet": 10, - "MultipleInheritanceFelinePut": 10, - "MultipleInheritanceCatGet": 10, - "MultipleInheritanceCatPut": 10, - "MultipleInheritanceKittenGet": 10, - "MultipleInheritanceKittenPut": 10, - "OptionalIntegerParameter": 10, - "OptionalIntegerProperty": 10, - "OptionalIntegerHeader": 10, - "OptionalStringParameter": 10, - "OptionalStringProperty": 10, - "OptionalStringHeader": 10, - "OptionalClassParameter": 10, - "OptionalClassProperty": 10, - "OptionalArrayParameter": 10, - "OptionalArrayProperty": 10, - "OptionalArrayHeader": 10 -} \ No newline at end of file diff --git a/test/azure/low-level/requirements.txt b/test/azure/low-level/requirements.txt deleted file mode 100644 index 7bb18aae729..00000000000 --- a/test/azure/low-level/requirements.txt +++ /dev/null @@ -1,22 +0,0 @@ -aiohttp;python_full_version>="3.5.2" -requests==2.20.0 -pytest -pytest-cov -pytest-asyncio==0.14.0;python_full_version>="3.5.2" -async_generator;python_full_version>="3.5.2" -azure-core==1.24.0 -azure-mgmt-core==1.3.0 -msrest==0.7.1 --e ./Expected/AcceptanceTests/AzureBodyDurationLowLevel --e ./Expected/AcceptanceTests/AzureParameterGroupingLowLevel --e ./Expected/AcceptanceTests/AzureReportLowLevel --e ./Expected/AcceptanceTests/AzureSpecialsLowLevel --e ./Expected/AcceptanceTests/CustomBaseUriLowLevel --e ./Expected/AcceptanceTests/CustomUrlPagingLowLevel --e ./Expected/AcceptanceTests/HeadLowLevel --e ./Expected/AcceptanceTests/HeadExceptionsLowLevel --e ./Expected/AcceptanceTests/LroLowLevel --e ./Expected/AcceptanceTests/LroWithParameterizedEndpointsLowLevel --e ./Expected/AcceptanceTests/PagingLowLevel --e ./Expected/AcceptanceTests/StorageManagementClientLowLevel --e ./Expected/AcceptanceTests/SubscriptionIdApiVersionLowLevel \ No newline at end of file diff --git a/test/azure/low-level/tox.ini b/test/azure/low-level/tox.ini deleted file mode 100644 index 95194458f1d..00000000000 --- a/test/azure/low-level/tox.ini +++ /dev/null @@ -1,16 +0,0 @@ -[tox] -envlist=py36, py310 -skipsdist=True - -[testenv] -passenv=* -deps= - -rrequirements.txt -commands= - pytest --cov=Expected - -[testenv:ci] -deps= - -rrequirements.txt -commands = - pytest --cov=Expected diff --git a/test/dpg/low-level/AcceptanceTests/asynctests/conftest.py b/test/dpg/low-level/AcceptanceTests/asynctests/conftest.py deleted file mode 100644 index 9e339411207..00000000000 --- a/test/dpg/low-level/AcceptanceTests/asynctests/conftest.py +++ /dev/null @@ -1,62 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -import sys -import subprocess -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 -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 - return subprocess.Popen(cmd) - - 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 -def terminate_server_process(process): - 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.""" - server = start_server_process() - yield - terminate_server_process(server) - -@pytest.fixture() -def base_send_request(): - async def send_request(client, request): - response = await client.send_request(request) - response.raise_for_status() - return response - return send_request diff --git a/test/dpg/low-level/AcceptanceTests/asynctests/test_service_driven_async.py b/test/dpg/low-level/AcceptanceTests/asynctests/test_service_driven_async.py deleted file mode 100644 index 07428614944..00000000000 --- a/test/dpg/low-level/AcceptanceTests/asynctests/test_service_driven_async.py +++ /dev/null @@ -1,123 +0,0 @@ - -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from azure.core.rest import HttpRequest - -from dpgservicedriveninitiallowlevel.aio import DPGClient as DPGClientInitial -from dpgservicedrivenupdateonelowlevel.aio import DPGClient as DPGClientUpdateOne - -from dpgservicedriveninitiallowlevel.rest import params as params_initial -from dpgservicedrivenupdateonelowlevel.rest import params as params_update_one - - -@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.fixture -def initial_send_request(initial_client, base_send_request): - async def _send_request(request): - return await base_send_request(initial_client, request) - return _send_request - -@pytest.fixture -def update_one_send_request(update_one_client, base_send_request): - async def _send_request(request): - return await base_send_request(update_one_client, request) - return _send_request - -@pytest.mark.asyncio -async def test_required_to_optional(initial_send_request, update_one_send_request): - request = params_initial.build_get_required_request(parameter="foo") - await initial_send_request(request) - - request = params_update_one.build_get_required_request(parameter="foo", new_parameter="bar") - await update_one_send_request(request) - -@pytest.mark.asyncio -async def test_add_optional_parameter_to_none(initial_send_request, update_one_send_request): - request = params_initial.build_head_no_params_request() - await initial_send_request(request) - - request = params_update_one.build_head_no_params_request(new_parameter="bar") - await update_one_send_request(request) - -@pytest.mark.asyncio -async def test_add_optional_parameter_to_required_optional(initial_send_request, update_one_send_request): - request = params_initial.build_put_required_optional_request(required_param="foo", optional_param="bar") - await initial_send_request(request) - - request = params_update_one.build_put_required_optional_request(required_param="foo", optional_param="bar", new_parameter="baz") - await update_one_send_request(request) - -@pytest.mark.asyncio -async def test_add_optional_parameter_to_optional(initial_send_request, update_one_send_request): - request = params_initial.build_get_optional_request(optional_param="foo") - await initial_send_request(request) - - request = params_update_one.build_get_optional_request(optional_param="foo", new_parameter="bar") - await update_one_send_request(request) - -@pytest.mark.asyncio -async def test_add_new_content_type(initial_send_request, update_one_send_request): - request = params_initial.build_post_parameters_request(json={ "url": "http://example.org/myimage.jpeg" }) - await initial_send_request(request) - - request = params_update_one.build_post_parameters_request(json={ "url": "http://example.org/myimage.jpeg" }) - await update_one_send_request(request) - request = params_update_one.build_post_parameters_request(content=b"hello", content_type="image/jpeg") - await update_one_send_request(request) - -@pytest.mark.asyncio -async def test_add_new_operation(update_one_send_request): - with pytest.raises(AttributeError): - params_initial.build_delete_parameters_request() - - request = params_update_one.build_delete_parameters_request() - await update_one_send_request(request) - -@pytest.mark.asyncio -async def test_add_new_path(update_one_send_request): - with pytest.raises(AttributeError): - params_initial.build_get_new_operation_request() - - request = params_update_one.build_get_new_operation_request() - response = await update_one_send_request(request) - assert response.json() == {'message': 'An object was successfully returned'} - -@pytest.mark.asyncio -async def test_glass_breaker(update_one_send_request): - request = HttpRequest(method="GET", url="/servicedriven/glassbreaker", params=[], headers={"Accept": "application/json"}) - response = await update_one_send_request(request) - assert response.status_code == 200 - assert response.json() == {'message': 'An object was successfully returned'} diff --git a/test/dpg/low-level/AcceptanceTests/conftest.py b/test/dpg/low-level/AcceptanceTests/conftest.py deleted file mode 100644 index 9e25a5a25c1..00000000000 --- a/test/dpg/low-level/AcceptanceTests/conftest.py +++ /dev/null @@ -1,62 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -import sys -import subprocess -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 -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 - return subprocess.Popen(cmd) - - 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 -def terminate_server_process(process): - 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.""" - server = start_server_process() - yield - terminate_server_process(server) - -@pytest.fixture() -def base_send_request(): - def send_request(client, request): - response = client.send_request(request) - response.raise_for_status() - return response - return send_request diff --git a/test/dpg/low-level/AcceptanceTests/test_service_driven.py b/test/dpg/low-level/AcceptanceTests/test_service_driven.py deleted file mode 100644 index a065c3ef531..00000000000 --- a/test/dpg/low-level/AcceptanceTests/test_service_driven.py +++ /dev/null @@ -1,115 +0,0 @@ - -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from azure.core.rest import HttpRequest - -from dpgservicedriveninitiallowlevel import DPGClient as DPGClientInitial -from dpgservicedrivenupdateonelowlevel import DPGClient as DPGClientUpdateOne - -from dpgservicedriveninitiallowlevel.rest import params as params_initial -from dpgservicedrivenupdateonelowlevel.rest import params as params_update_one - - -@pytest.fixture -def initial_client(): - with DPGClientInitial() as client: - yield client - -@pytest.fixture -def update_one_client(): - with DPGClientUpdateOne() as client: - yield client - -@pytest.fixture -def initial_send_request(initial_client, base_send_request): - def _send_request(request): - return base_send_request(initial_client, request) - return _send_request - -@pytest.fixture -def update_one_send_request(update_one_client, base_send_request): - def _send_request(request): - return base_send_request(update_one_client, request) - return _send_request - - -def test_required_to_optional(initial_send_request, update_one_send_request): - request = params_initial.build_get_required_request(parameter="foo") - initial_send_request(request) - - request = params_update_one.build_get_required_request(parameter="foo", new_parameter="bar") - update_one_send_request(request) - -def test_add_optional_parameter_to_none(initial_send_request, update_one_send_request): - request = params_initial.build_head_no_params_request() - initial_send_request(request) - - request = params_update_one.build_head_no_params_request(new_parameter="bar") - update_one_send_request(request) - -def test_add_optional_parameter_to_required_optional(initial_send_request, update_one_send_request): - request = params_initial.build_put_required_optional_request(required_param="foo", optional_param="bar") - initial_send_request(request) - - request = params_update_one.build_put_required_optional_request(required_param="foo", optional_param="bar", new_parameter="baz") - update_one_send_request(request) - -def test_add_optional_parameter_to_optional(initial_send_request, update_one_send_request): - request = params_initial.build_get_optional_request(optional_param="foo") - initial_send_request(request) - - request = params_update_one.build_get_optional_request(optional_param="foo", new_parameter="bar") - update_one_send_request(request) - -def test_add_new_content_type(initial_send_request, update_one_send_request): - request = params_initial.build_post_parameters_request(json={ "url": "http://example.org/myimage.jpeg" }) - initial_send_request(request) - - request = params_update_one.build_post_parameters_request(json={ "url": "http://example.org/myimage.jpeg" }) - update_one_send_request(request) - request = params_update_one.build_post_parameters_request(content=b"hello", content_type="image/jpeg") - update_one_send_request(request) - -def test_add_new_operation(update_one_send_request): - with pytest.raises(AttributeError): - params_initial.build_delete_parameters_request() - - request = params_update_one.build_delete_parameters_request() - update_one_send_request(request) - -def test_add_new_path(update_one_send_request): - with pytest.raises(AttributeError): - params_initial.build_get_new_operation_request() - - request = params_update_one.build_get_new_operation_request() - assert update_one_send_request(request).json() == {'message': 'An object was successfully returned'} - -def test_glass_breaker(update_one_send_request): - request = HttpRequest(method="GET", url="/servicedriven/glassbreaker", params=[], headers={"Accept": "application/json"}) - response = update_one_send_request(request) - assert response.status_code == 200 - assert response.json() == {'message': 'An object was successfully returned'} diff --git a/test/dpg/low-level/AcceptanceTests/test_zzz.py b/test/dpg/low-level/AcceptanceTests/test_zzz.py deleted file mode 100644 index 67d069e0477..00000000000 --- a/test/dpg/low-level/AcceptanceTests/test_zzz.py +++ /dev/null @@ -1,74 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import platform -import warnings -from azure.core.rest import HttpRequest - -from dpgservicedriveninitiallowlevel import DPGClient - - -class TestAcceptance(object): - - def test_ensure_coverage(self): - client = DPGClient() - 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 = { - } - - # Please add missing features or failing tests here - missing_features_or_bugs = { - } - for name in support_dict: - if "DPG" not in name: - # this folder only does dpg - missing_features_or_bugs[name] = 1 - - print("Coverage:") - self._print_report(support_dict, 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) - for s in not_supported.keys(): - print("IGNORING {0}".format(s)) - - if missing_features_or_bugs: - report.update(missing_features_or_bugs) - for s in missing_features_or_bugs.keys(): - print("PENDING {0}".format(s)) - - failed = [k for k, v in report.items() if v == 0] - for s in failed: - 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)) - - assert 0 == len(failed) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/__init__.py deleted file mode 100644 index f5332de4198..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import DPGClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["DPGClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_client.py deleted file mode 100644 index 392fee42334..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import DPGClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: # pylint: disable=client-accepts-api-version-keyword - """DPG Swagger that tests our ability to grow up. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgcustomizationcustomizedlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgcustomizationcustomizedlowlevel.rest import build_get_model_request - >>> request = build_get_model_request(mode, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> DPGClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_configuration.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_configuration.py deleted file mode 100644 index a49fe18c91a..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class DPGClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for DPGClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(DPGClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "dpgcustomizationcustomized/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_dpg_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_dpg_client.py deleted file mode 100644 index 4de7b00f7ce..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_dpg_client.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from msrest import Deserializer, Serializer - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: - """DPG Swagger that tests our ability to grow up. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - - self._config = DPGClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgcustomizationcustomizedlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgcustomizationcustomizedlowlevel.rest import build_get_model_request - >>> request = build_get_model_request(mode, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> DPGClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_patch.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_serialization.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_vendor.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_version.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/__init__.py deleted file mode 100644 index 7ddaafaf471..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import DPGClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["DPGClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_client.py deleted file mode 100644 index 116a94d4279..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: # pylint: disable=client-accepts-api-version-keyword - """DPG Swagger that tests our ability to grow up. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgcustomizationcustomizedlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgcustomizationcustomizedlowlevel.rest import build_get_model_request - >>> request = build_get_model_request(mode, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "DPGClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_configuration.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_configuration.py deleted file mode 100644 index c6b02806066..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class DPGClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for DPGClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(DPGClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "dpgcustomizationcustomized/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_dpg_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_dpg_client.py deleted file mode 100644 index 7011655684f..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_dpg_client.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from msrest import Deserializer, Serializer - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: - """DPG Swagger that tests our ability to grow up. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgcustomizationcustomizedlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgcustomizationcustomizedlowlevel.rest import build_get_model_request - >>> request = build_get_model_request(mode, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "DPGClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_patch.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/py.typed b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/rest/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/rest/__init__.py deleted file mode 100644 index 11a2c8a0ad2..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/rest/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_model_request -from ._request_builders import build_post_model_request -from ._request_builders import build_get_pages_request -from ._request_builders import build_lro_request - -__all__ = [ - "build_get_model_request", - "build_post_model_request", - "build_get_pages_request", - "build_lro_request", -] diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/rest/_request_builders.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/rest/_request_builders.py deleted file mode 100644 index 211372b9bda..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/dpgcustomizationcustomizedlowlevel/rest/_request_builders.py +++ /dev/null @@ -1,232 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer -from .._vendor import _format_url_section - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_model_request(mode: str, **kwargs: Any) -> HttpRequest: - """Get models that you will either return to end users as a raw body, or with a model added during - grow up. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/customization/model/{mode}" - path_format_arguments = { - "mode": _SERIALIZER.url("mode", mode, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_model_request( - mode: str, *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Post either raw response as a model and pass in 'raw' for mode, or grow up your operation to - take a model instead, and put in 'model' as mode. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :keyword json: Please put {'hello': 'world!'}. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "hello": "str" # Required. - } - """ - - -@overload -def build_post_model_request( - mode: str, *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Post either raw response as a model and pass in 'raw' for mode, or grow up your operation to - take a model instead, and put in 'model' as mode. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :keyword content: Please put {'hello': 'world!'}. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_model_request(mode: str, **kwargs: Any) -> HttpRequest: - """Post either raw response as a model and pass in 'raw' for mode, or grow up your operation to - take a model instead, and put in 'model' as mode. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :keyword json: Please put {'hello': 'world!'}. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/customization/model/{mode}" - path_format_arguments = { - "mode": _SERIALIZER.url("mode", mode, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_get_pages_request(mode: str, **kwargs: Any) -> HttpRequest: - """Get pages that you will either return to users in pages of raw bodies, or pages of models - following growup. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/customization/paging/{mode}" - path_format_arguments = { - "mode": _SERIALIZER.url("mode", mode, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_lro_request(mode: str, **kwargs: Any) -> HttpRequest: - """Long running put request that will either return to end users a final payload of a raw body, or - a final payload of a model after the SDK has grown up. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/customization/lro/{mode}" - path_format_arguments = { - "mode": _SERIALIZER.url("mode", mode, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/setup.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/setup.py deleted file mode 100644 index 1924c3b146a..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationCustomizedLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "dpgcustomizationcustomized" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="dpgcustomizationcustomized", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - DPG Swagger that tests our ability to grow up. - """, -) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/__init__.py deleted file mode 100644 index f5332de4198..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import DPGClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["DPGClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_client.py deleted file mode 100644 index 911f33bb87c..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import DPGClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: # pylint: disable=client-accepts-api-version-keyword - """DPG Swagger that tests our ability to grow up. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgcustomizationinitiallowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgcustomizationinitiallowlevel.rest import build_get_model_request - >>> request = build_get_model_request(mode, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> DPGClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_configuration.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_configuration.py deleted file mode 100644 index eafc84ac958..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class DPGClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for DPGClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(DPGClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "dpgcustomizationinitial/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_dpg_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_dpg_client.py deleted file mode 100644 index 328137105fc..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_dpg_client.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from msrest import Deserializer, Serializer - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: - """DPG Swagger that tests our ability to grow up. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - - self._config = DPGClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgcustomizationinitiallowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgcustomizationinitiallowlevel.rest import build_get_model_request - >>> request = build_get_model_request(mode, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> DPGClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_patch.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_serialization.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_vendor.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_version.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/__init__.py deleted file mode 100644 index 7ddaafaf471..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import DPGClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["DPGClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_client.py deleted file mode 100644 index 6ea7f7cdb2c..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: # pylint: disable=client-accepts-api-version-keyword - """DPG Swagger that tests our ability to grow up. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgcustomizationinitiallowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgcustomizationinitiallowlevel.rest import build_get_model_request - >>> request = build_get_model_request(mode, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "DPGClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_configuration.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_configuration.py deleted file mode 100644 index 474127abb36..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class DPGClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for DPGClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(DPGClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "dpgcustomizationinitial/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_dpg_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_dpg_client.py deleted file mode 100644 index 891d3514e65..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_dpg_client.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from msrest import Deserializer, Serializer - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: - """DPG Swagger that tests our ability to grow up. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgcustomizationinitiallowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgcustomizationinitiallowlevel.rest import build_get_model_request - >>> request = build_get_model_request(mode, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "DPGClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_patch.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/py.typed b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/rest/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/rest/__init__.py deleted file mode 100644 index 11a2c8a0ad2..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/rest/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_model_request -from ._request_builders import build_post_model_request -from ._request_builders import build_get_pages_request -from ._request_builders import build_lro_request - -__all__ = [ - "build_get_model_request", - "build_post_model_request", - "build_get_pages_request", - "build_lro_request", -] diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/rest/_request_builders.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/rest/_request_builders.py deleted file mode 100644 index 211372b9bda..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/dpgcustomizationinitiallowlevel/rest/_request_builders.py +++ /dev/null @@ -1,232 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer -from .._vendor import _format_url_section - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_model_request(mode: str, **kwargs: Any) -> HttpRequest: - """Get models that you will either return to end users as a raw body, or with a model added during - grow up. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/customization/model/{mode}" - path_format_arguments = { - "mode": _SERIALIZER.url("mode", mode, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_model_request( - mode: str, *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Post either raw response as a model and pass in 'raw' for mode, or grow up your operation to - take a model instead, and put in 'model' as mode. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :keyword json: Please put {'hello': 'world!'}. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "hello": "str" # Required. - } - """ - - -@overload -def build_post_model_request( - mode: str, *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Post either raw response as a model and pass in 'raw' for mode, or grow up your operation to - take a model instead, and put in 'model' as mode. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :keyword content: Please put {'hello': 'world!'}. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_model_request(mode: str, **kwargs: Any) -> HttpRequest: - """Post either raw response as a model and pass in 'raw' for mode, or grow up your operation to - take a model instead, and put in 'model' as mode. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :keyword json: Please put {'hello': 'world!'}. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/customization/model/{mode}" - path_format_arguments = { - "mode": _SERIALIZER.url("mode", mode, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_get_pages_request(mode: str, **kwargs: Any) -> HttpRequest: - """Get pages that you will either return to users in pages of raw bodies, or pages of models - following growup. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/customization/paging/{mode}" - path_format_arguments = { - "mode": _SERIALIZER.url("mode", mode, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_lro_request(mode: str, **kwargs: Any) -> HttpRequest: - """Long running put request that will either return to end users a final payload of a raw body, or - a final payload of a model after the SDK has grown up. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param mode: The mode with which you'll be handling your returned body. 'raw' for just dealing - with the raw body, and 'model' if you are going to convert the raw body to a customized body - before returning to users. Required. - :type mode: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/customization/lro/{mode}" - path_format_arguments = { - "mode": _SERIALIZER.url("mode", mode, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/setup.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/setup.py deleted file mode 100644 index d25cac43ffa..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGCustomizationInitialLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "dpgcustomizationinitial" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="dpgcustomizationinitial", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - DPG Swagger that tests our ability to grow up. - """, -) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/__init__.py deleted file mode 100644 index f5332de4198..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import DPGClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["DPGClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_client.py deleted file mode 100644 index fe5da6335c3..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import DPGClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: # pylint: disable=client-accepts-api-version-keyword - """DPG Swagger, this is the initial swagger a service could do. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgservicedriveninitiallowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgservicedriveninitiallowlevel.rest import params - >>> request = params.build_head_no_params_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> DPGClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_configuration.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_configuration.py deleted file mode 100644 index aa0da1d6a59..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class DPGClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for DPGClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(DPGClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "dpgservicedriveninitial/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_dpg_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_dpg_client.py deleted file mode 100644 index a25571b449d..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_dpg_client.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from msrest import Deserializer, Serializer - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: - """DPG Swagger, this is the initial swagger a service could do. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - - self._config = DPGClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgservicedriveninitiallowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgservicedriveninitiallowlevel.rest import params - >>> request = params.build_head_no_params_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> DPGClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_patch.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_serialization.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_version.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/__init__.py deleted file mode 100644 index 7ddaafaf471..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import DPGClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["DPGClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_client.py deleted file mode 100644 index 9592f913bd0..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: # pylint: disable=client-accepts-api-version-keyword - """DPG Swagger, this is the initial swagger a service could do. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgservicedriveninitiallowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgservicedriveninitiallowlevel.rest import params - >>> request = params.build_head_no_params_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "DPGClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_configuration.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_configuration.py deleted file mode 100644 index f1f0120e41b..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class DPGClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for DPGClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(DPGClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "dpgservicedriveninitial/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_dpg_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_dpg_client.py deleted file mode 100644 index 1325ff59635..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_dpg_client.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from msrest import Deserializer, Serializer - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: - """DPG Swagger, this is the initial swagger a service could do. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgservicedriveninitiallowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgservicedriveninitiallowlevel.rest import params - >>> request = params.build_head_no_params_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "DPGClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_patch.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/py.typed b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/params/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/params/__init__.py deleted file mode 100644 index 94039b6f3da..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/params/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_head_no_params_request -from ._request_builders import build_get_required_request -from ._request_builders import build_put_required_optional_request -from ._request_builders import build_post_parameters_request -from ._request_builders import build_get_optional_request - -__all__ = [ - "build_head_no_params_request", - "build_get_required_request", - "build_put_required_optional_request", - "build_post_parameters_request", - "build_get_optional_request", -] diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/params/_request_builders.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/params/_request_builders.py deleted file mode 100644 index ab11c263053..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/dpgservicedriveninitiallowlevel/rest/params/_request_builders.py +++ /dev/null @@ -1,236 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_head_no_params_request(**kwargs: Any) -> HttpRequest: - """Head request, no params. - Initially has no query parameters. After evolution, a new optional query parameter is added. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/serviceDriven/parameters" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_get_required_request(*, parameter: str, **kwargs: Any) -> HttpRequest: - """Get true Boolean value on path. - Initially only has one required Query Parameter. After evolution, a new optional query - parameter is added. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword parameter: I am a required parameter. Required. - :paramtype parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/serviceDriven/parameters" - - # Construct parameters - _params["parameter"] = _SERIALIZER.query("parameter", parameter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_put_required_optional_request( - *, required_param: str, optional_param: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Initially has one required query parameter and one optional query parameter. After evolution, - a new optional query parameter is added. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword required_param: I am a required parameter. Required. - :paramtype required_param: str - :keyword optional_param: I am an optional parameter. Default value is None. - :paramtype optional_param: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/serviceDriven/parameters" - - # Construct parameters - _params["requiredParam"] = _SERIALIZER.query("required_param", required_param, "str") - if optional_param is not None: - _params["optionalParam"] = _SERIALIZER.query("optional_param", optional_param, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -@overload -def build_post_parameters_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """POST a JSON. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: I am a body parameter. My only valid JSON entry is { url: - "http://example.org/myimage.jpeg" }. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "url": "str" # Required. - } - """ - - -@overload -def build_post_parameters_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """POST a JSON. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: I am a body parameter. My only valid JSON entry is { url: - "http://example.org/myimage.jpeg" }. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_parameters_request(**kwargs: Any) -> HttpRequest: - """POST a JSON. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: I am a body parameter. My only valid JSON entry is { url: - "http://example.org/myimage.jpeg" }. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/serviceDriven/parameters" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_get_optional_request(*, optional_param: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Get true Boolean value on path. - Initially has one optional query parameter. After evolution, a new optional query parameter is - added. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword optional_param: I am an optional parameter. Default value is None. - :paramtype optional_param: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/serviceDriven/moreParameters" - - # Construct parameters - if optional_param is not None: - _params["optionalParam"] = _SERIALIZER.query("optional_param", optional_param, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/setup.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/setup.py deleted file mode 100644 index 9172bce794d..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "dpgservicedriveninitial" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="dpgservicedriveninitial", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - DPG Swagger, this is the initial swagger a service could do. - """, -) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/__init__.py deleted file mode 100644 index f5332de4198..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import DPGClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["DPGClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_client.py deleted file mode 100644 index dd27b5e5bed..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import DPGClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: # pylint: disable=client-accepts-api-version-keyword - """DPG Swagger, this is the initial swagger a service could do. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgservicedrivenupdateonelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgservicedrivenupdateonelowlevel.rest import params - >>> request = params.build_head_no_params_request(new_parameter=new_parameter, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> DPGClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_configuration.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_configuration.py deleted file mode 100644 index aadf7ac14e2..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class DPGClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for DPGClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(DPGClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "dpgservicedrivenupdateone/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_dpg_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_dpg_client.py deleted file mode 100644 index e30e2614987..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_dpg_client.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from msrest import Deserializer, Serializer - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: - """DPG Swagger, this is the initial swagger a service could do. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - - self._config = DPGClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgservicedrivenupdateonelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgservicedrivenupdateonelowlevel.rest import params - >>> request = params.build_head_no_params_request(new_parameter=new_parameter, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> DPGClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_patch.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_serialization.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_version.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/__init__.py deleted file mode 100644 index 7ddaafaf471..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import DPGClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["DPGClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_client.py deleted file mode 100644 index b013060440e..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: # pylint: disable=client-accepts-api-version-keyword - """DPG Swagger, this is the initial swagger a service could do. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgservicedrivenupdateonelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgservicedrivenupdateonelowlevel.rest import params - >>> request = params.build_head_no_params_request(new_parameter=new_parameter, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "DPGClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_configuration.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_configuration.py deleted file mode 100644 index 5bb81087858..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class DPGClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for DPGClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(DPGClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "dpgservicedrivenupdateone/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_dpg_client.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_dpg_client.py deleted file mode 100644 index c7c6459eef6..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_dpg_client.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from msrest import Deserializer, Serializer - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from ._configuration import DPGClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class DPGClient: - """DPG Swagger, this is the initial swagger a service could do. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = DPGClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `dpgservicedrivenupdateonelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from dpgservicedrivenupdateonelowlevel.rest import params - >>> request = params.build_head_no_params_request(new_parameter=new_parameter, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/python/protocol/quickstart - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "DPGClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_patch.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/py.typed b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/params/__init__.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/params/__init__.py deleted file mode 100644 index 1df5a55922b..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/params/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_head_no_params_request -from ._request_builders import build_get_required_request -from ._request_builders import build_put_required_optional_request -from ._request_builders import build_post_parameters_request -from ._request_builders import build_delete_parameters_request -from ._request_builders import build_get_optional_request -from ._request_builders import build_get_new_operation_request - -__all__ = [ - "build_head_no_params_request", - "build_get_required_request", - "build_put_required_optional_request", - "build_post_parameters_request", - "build_delete_parameters_request", - "build_get_optional_request", - "build_get_new_operation_request", -] diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/params/_request_builders.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/params/_request_builders.py deleted file mode 100644 index 20752c11c9f..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/dpgservicedrivenupdateonelowlevel/rest/params/_request_builders.py +++ /dev/null @@ -1,304 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_head_no_params_request(*, new_parameter: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Head request, no params. Initially has no query parameters. After evolution, a new optional - query parameter is added. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword new_parameter: I'm a new input optional parameter. Default value is None. - :paramtype new_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/serviceDriven/parameters" - - # Construct parameters - if new_parameter is not None: - _params["new_parameter"] = _SERIALIZER.query("new_parameter", new_parameter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_required_request(*, parameter: str, new_parameter: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Get true Boolean value on path. - Initially only has one required Query Parameter. After evolution, a new optional query - parameter is added. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword parameter: I am a required parameter. Required. - :paramtype parameter: str - :keyword new_parameter: I'm a new input optional parameter. Default value is None. - :paramtype new_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/serviceDriven/parameters" - - # Construct parameters - _params["parameter"] = _SERIALIZER.query("parameter", parameter, "str") - if new_parameter is not None: - _params["new_parameter"] = _SERIALIZER.query("new_parameter", new_parameter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_put_required_optional_request( - *, required_param: str, optional_param: Optional[str] = None, new_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Initially has one required query parameter and one optional query parameter. After evolution, - a new optional query parameter is added. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword required_param: I am a required parameter. Required. - :paramtype required_param: str - :keyword optional_param: I am an optional parameter. Default value is None. - :paramtype optional_param: str - :keyword new_parameter: I'm a new input optional parameter. Default value is None. - :paramtype new_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/serviceDriven/parameters" - - # Construct parameters - _params["requiredParam"] = _SERIALIZER.query("required_param", required_param, "str") - if optional_param is not None: - _params["optionalParam"] = _SERIALIZER.query("optional_param", optional_param, "str") - if new_parameter is not None: - _params["new_parameter"] = _SERIALIZER.query("new_parameter", new_parameter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -@overload -def build_post_parameters_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """POST a JSON or a JPEG. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: I am a body parameter with a new content type. My only valid JSON entry is { - url: "http://example.org/myimage.jpeg" }. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "url": "str" # Required. - } - """ - - -@overload -def build_post_parameters_request(*, content_type: str, content: IO, **kwargs: Any) -> HttpRequest: - """POST a JSON or a JPEG. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'image/jpeg'. Required. - :paramtype content_type: str - :keyword content: I am a body parameter with a new content type. My only valid JSON entry is { - url: "http://example.org/myimage.jpeg" }. Required. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_parameters_request(**kwargs: Any) -> HttpRequest: - """POST a JSON or a JPEG. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: I am a body parameter with a new content type. My only valid JSON entry is { - url: "http://example.org/myimage.jpeg" }. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json', - 'image/jpeg'. Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/serviceDriven/parameters" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_delete_parameters_request(**kwargs: Any) -> HttpRequest: - """Delete something. - Initially the path exists but there is no delete method. After evolution this is a new method - in a known path. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/serviceDriven/parameters" - - return HttpRequest(method="DELETE", url=_url, **kwargs) - - -def build_get_optional_request( - *, optional_param: Optional[str] = None, new_parameter: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Get true Boolean value on path. - Initially has one optional query parameter. After evolution, a new optional query parameter is - added. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword optional_param: I am an optional parameter. Default value is None. - :paramtype optional_param: str - :keyword new_parameter: I'm a new input optional parameter. Default value is None. - :paramtype new_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/serviceDriven/moreParameters" - - # Construct parameters - if optional_param is not None: - _params["optionalParam"] = _SERIALIZER.query("optional_param", optional_param, "str") - if new_parameter is not None: - _params["new_parameter"] = _SERIALIZER.query("new_parameter", new_parameter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_new_operation_request(**kwargs: Any) -> HttpRequest: - """I'm a new operation. - Initiallty neither path or method exist for this operation. After evolution, this is a new - method in a new path. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/serviceDriven/newPath" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/setup.py b/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/setup.py deleted file mode 100644 index 85e1a70bca2..00000000000 --- a/test/dpg/low-level/Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "dpgservicedrivenupdateone" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="dpgservicedrivenupdateone", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - DPG Swagger, this is the initial swagger a service could do. - """, -) diff --git a/test/dpg/low-level/requirements.txt b/test/dpg/low-level/requirements.txt deleted file mode 100644 index 5d93630c0d5..00000000000 --- a/test/dpg/low-level/requirements.txt +++ /dev/null @@ -1,9 +0,0 @@ -aiohttp;python_full_version>="3.5.2" -requests==2.20.0 -pytest -pytest-cov -pytest-asyncio==0.14.0;python_full_version>="3.5.2" -async_generator;python_full_version>="3.5.2" -azure-core==1.24.0 --e ./Expected/AcceptanceTests/DPGServiceDrivenInitialLowLevel/ --e ./Expected/AcceptanceTests/DPGServiceDrivenUpdateOneLowLevel/ \ No newline at end of file diff --git a/test/dpg/low-level/tox.ini b/test/dpg/low-level/tox.ini deleted file mode 100644 index 9936a3d27ac..00000000000 --- a/test/dpg/low-level/tox.ini +++ /dev/null @@ -1,10 +0,0 @@ -[tox] -envlist=py36, py310 -skipsdist=True - -[testenv:ci] -passenv=* -deps= - -rrequirements.txt -commands = - pytest --cov=Expected AcceptanceTests \ No newline at end of file diff --git a/test/vanilla/low-level/AcceptanceTests/__init__.py b/test/vanilla/low-level/AcceptanceTests/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/__init__.py b/test/vanilla/low-level/AcceptanceTests/asynctests/__init__.py deleted file mode 100644 index e69de29bb2d..00000000000 diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/conftest.py b/test/vanilla/low-level/AcceptanceTests/asynctests/conftest.py deleted file mode 100644 index 445a83c4d06..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/conftest.py +++ /dev/null @@ -1,50 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest - -@pytest.fixture() -def base_send_request(): - async def send_request(client, request): - response = await client.send_request(request) - response.raise_for_status() - return response - return send_request - -@pytest.fixture() -def base_send_request_json_response(): - async def send_request_json_response(client, request): - response = await client.send_request(request) - response.raise_for_status() - return response.json() - return send_request_json_response - -@pytest.fixture() -def base_make_stream_request(): - async def make_stream_request(client, request): - response = await client.send_request(request, stream=True) - response.raise_for_status() - return response.stream_download() - return make_stream_request diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_additional_properties.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_additional_properties.py deleted file mode 100644 index ca8629c361c..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_additional_properties.py +++ /dev/null @@ -1,135 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from async_generator import yield_, async_generator -from additionalpropertieslowlevel.aio import AdditionalPropertiesClient -from additionalpropertieslowlevel.rest import pets - -@pytest.fixture -@async_generator -async def client(): - async with AdditionalPropertiesClient() as client: - await yield_(client) - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_create_ap_true(send_request_json_response): - json = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - }, - "id": 1, - "name": "Puppy", - } - request = pets.build_create_ap_true_request(json=json) - response = await send_request_json_response(request) - assert response["birthdate"] == '2017-12-13T02:29:51Z' - -@pytest.mark.asyncio -async def test_create_cat_ap_true(send_request_json_response): - json = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': {'color': 'Red'}, - 'id': 1, - 'name': 'Lisa', - 'friendly': True - } - request = pets.build_create_cat_ap_true_request(json=json) - response = await send_request_json_response(request) - assert response['birthdate'] == '2017-12-13T02:29:51Z' - -@pytest.mark.asyncio -async def test_create_ap_object(send_request_json_response): - json = { - "id": 2, - "name": "Hira", - 'siblings': [{ - 'id': 1, - 'name': 'Puppy', - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - } - }], - 'picture': '//////4=' - } - request = pets.build_create_ap_object_request(json=json) - response = await send_request_json_response(request) - assert response['siblings'][0]['birthdate'] == '2017-12-13T02:29:51Z' - -@pytest.mark.asyncio -async def test_create_ap_string(send_request_json_response): - json = { - "id": 3, - "name": 'Tommy', - 'color': 'red', - 'weight': '10 kg', - 'city': 'Bombay' - } - request = pets.build_create_ap_string_request(json=json) - response = await send_request_json_response(request) - assert response['color'] == 'red' - -@pytest.mark.asyncio -async def test_create_ap_in_properties(send_request_json_response): - json = { - "id": 4, - "name": 'Bunny', - "additionalProperties": { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } - } - request = pets.build_create_ap_in_properties_request(json=json) - response = await send_request_json_response(request) - assert response["additionalProperties"]['weight'] == 599 - -@pytest.mark.asyncio -async def test_create_ap_in_properties_with_ap_string(send_request_json_response): - json = { - "id": 5, - "name": 'Funny', - "@odata.location":'westus', - 'color': 'red', - 'city': 'Seattle', - 'food': 'tikka masala', - "additionalProperties": { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } - } - request = pets.build_create_ap_in_properties_with_ap_string_request(json=json) - response = await send_request_json_response(request) - assert response['color'] == 'red' - assert response['additionalProperties']['weight'] == 599 \ No newline at end of file diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_anything.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_anything.py deleted file mode 100644 index 7d86f459b25..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_anything.py +++ /dev/null @@ -1,78 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from async_generator import yield_, async_generator -from anythinglowlevel.aio import AnythingClient -from anythinglowlevel import rest - -@pytest.fixture -@async_generator -async def client(): - async with AnythingClient() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_get_string(send_request_json_response): - request = rest.build_get_string_request() - assert await send_request_json_response(request) == 'anything' - -@pytest.mark.asyncio -async def test_put_string(send_request): - request = rest.build_put_string_request(json="anything") - await send_request(request) - -@pytest.mark.asyncio -async def test_get_object(send_request_json_response): - request = rest.build_get_object_request() - assert await send_request_json_response(request) == {"message": "An object was successfully returned"} - -@pytest.mark.asyncio -async def test_put_object(send_request): - request = rest.build_put_object_request(json={'foo': 'bar'}) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_array(send_request_json_response): - request = rest.build_get_array_request() - assert await send_request_json_response(request) == ['foo', 'bar'] - -@pytest.mark.asyncio -async def test_put_array(send_request): - request = rest.build_put_array_request(json=['foo', 'bar']) - await send_request(request) - diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_array.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_array.py deleted file mode 100644 index 5728511db44..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_array.py +++ /dev/null @@ -1,423 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import json -import isodate -from async_generator import yield_, async_generator -from azure.core.exceptions import DecodeError -from datetime import date, datetime, timedelta -from base64 import b64encode -from bodyarraylowlevel.aio import AutoRestSwaggerBATArrayService -from bodyarraylowlevel.rest import array -from bodyarraylowlevel._serialization import Serializer, Deserializer - -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") - datetime2 = isodate.parse_datetime("1980-01-02T00:11:35Z") - 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"}] - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.fixture -def serializer(): - return Serializer() - -@pytest.fixture -def deserializer(): - return Deserializer() - - -@pytest.mark.asyncio -async def test_empty(send_request, send_request_json_response): - request = array.build_get_empty_request() - - assert [] == await send_request_json_response(request) - - request = array.build_get_null_request() - response = await send_request(request) - assert response.text() == '' - - request = array.build_put_empty_request(json=[]) - await send_request(request) - -@pytest.mark.asyncio -async def test_boolean_tfft(send_request, send_request_json_response): - request = array.build_get_boolean_tfft_request() - assert [True, False, False, True] == await send_request_json_response(request) - request = array.build_put_boolean_tfft_request(json=[True, False, False, True]) - await send_request(request) - -@pytest.mark.asyncio -async def test_integer_valid(send_request, send_request_json_response): - request = array.build_get_integer_valid_request() - assert [1, -1, 3, 300] == await send_request_json_response(request) - request = array.build_put_integer_valid_request(json=[1, -1, 3, 300]) - await send_request(request) - -@pytest.mark.asyncio -async def test_long_valid(send_request, send_request_json_response): - request = array.build_get_long_valid_request() - assert [1, -1, 3, 300] == await send_request_json_response(request) - request = array.build_put_long_valid_request(json=[1, -1, 3, 300]) - await send_request(request) - -@pytest.mark.asyncio -async def test_float_valid(send_request, send_request_json_response): - request = array.build_get_float_valid_request() - assert [0, -0.01, -1.2e20] == await send_request_json_response(request) - request = array.build_put_float_valid_request(json=[0, -0.01, -1.2e20]) - await send_request(request) - -@pytest.mark.asyncio -async def test_double_valid(send_request, send_request_json_response): - request = array.build_get_double_valid_request() - assert [0, -0.01, -1.2e20] == await send_request_json_response(request) - request = array.build_put_double_valid_request(json=[0, -0.01, -1.2e20]) - await send_request(request) - -@pytest.mark.asyncio -async def test_string_valid(send_request, send_request_json_response): - request = array.build_get_string_valid_request() - assert ["foo1", "foo2", "foo3"] == await send_request_json_response(request) - request = array.build_put_string_valid_request(json=["foo1", "foo2", "foo3"]) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_string_with_null(send_request_json_response): - request = array.build_get_string_with_null_request() - assert ["foo", None, "foo2"] == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_string_with_invalid(send_request_json_response): - request = array.build_get_string_with_invalid_request() - - # response differs from convenience layer - # this is bc in convenence layer we tell the deserializer to deserialize it fully as a list of string - assert ["foo", 123, "foo2"] == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_uuid_valid(send_request, send_request_json_response): - request = array.build_get_uuid_valid_request() - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"] == await send_request_json_response(request) - request = array.build_put_uuid_valid_request(json=["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"]) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_uuid_invalid_chars(send_request, send_request_json_response): - #Handles invalid characters without error because of no guid class - request = array.build_get_uuid_invalid_chars_request() - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "foo"] == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_date_valid(send_request, send_request_json_response): - def datetime_handler(x): - if isinstance(x, datetime.date): - return x.isoformat() - raise TypeError("Unknown type") - date1 = isodate.parse_date("2000-12-01") - date2 = isodate.parse_date("1980-01-02") - date3 = isodate.parse_date("1492-10-12") - - request = array.build_get_date_valid_request() - assert await send_request_json_response(request), [date1, date2 == date3] - request = array.build_put_date_valid_request(json=[str(date1), str(date2), str(date3)]) # dates are not json serializable - await send_request(request) - -@pytest.mark.asyncio -async def test_date_time_valid(send_request, send_request_json_response, datetimes, serializer): - request = array.build_get_date_time_valid_request() - - assert await send_request_json_response(request), [datetimes[0], datetimes[1] == datetimes[2]] - request = array.build_put_date_time_valid_request(json=[serializer.serialize_iso(datetime) for datetime in datetimes]) - await send_request(request) - -@pytest.mark.asyncio -async def test_date_time_rfc1123_valid(send_request, send_request_json_response, datetimes, serializer): - request = array.build_get_date_time_rfc1123_valid_request() - assert await send_request_json_response(request), [datetimes[0], datetimes[1] == datetimes[2]] - request = array.build_put_date_time_rfc1123_valid_request(json=[serializer.serialize_rfc(datetime) for datetime in datetimes]) - await send_request(request) - -@pytest.mark.asyncio -async def test_duration_valid(send_request, send_request_json_response): - duration1 = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) - duration2 = timedelta(days=5, hours=1) - - request = array.build_get_duration_valid_request() - assert await send_request_json_response(request), [duration1 == duration2] - request = array.build_put_duration_valid_request(json=[isodate.duration_isoformat(duration1), isodate.duration_isoformat(duration2)]) - await send_request(request) - -@pytest.mark.asyncio -async def test_byte_valid(send_request, send_request_json_response): - bytes1 = bytearray([0x0FF, 0x0FF, 0x0FF, 0x0FA]) - bytes2 = bytearray([0x01, 0x02, 0x03]) - bytes3 = bytearray([0x025, 0x029, 0x043]) - - request = array.build_get_byte_valid_request() - assert await send_request_json_response(request), [bytes1, bytes2 == bytes3] - request = array.build_put_byte_valid_request(json=[b64encode(b).decode() for b in [bytes1, bytes2, bytes3]]) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_byte_invalid_null(send_request_json_response): - request = array.build_get_byte_invalid_null_request() - assert await send_request_json_response(request), [bytearray([0x0AB, 0x0AC, 0x0AD]) == None] - -@pytest.mark.asyncio -async def test_get_complex_null(send_request): - request = array.build_get_complex_null_request() - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_get_complex_empty(send_request_json_response): - request = array.build_get_complex_empty_request() - assert [] == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_complex_valid(send_request, send_request_json_response, products): - request = array.build_get_complex_valid_request() - assert products == await send_request_json_response(request) - request = array.build_put_complex_valid_request(json=products) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_array_valid(send_request, send_request_json_response): - listlist = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]] - request = array.build_get_array_valid_request() - assert listlist == await send_request_json_response(request) - request = array.build_put_array_valid_request(json=listlist) - await send_request(request) - - -@pytest.mark.asyncio -async def test_dictionary_valid(send_request, send_request_json_response, listdict): - request = array.build_get_dictionary_valid_request() - assert listdict == await send_request_json_response(request) - request = array.build_put_dictionary_valid_request(json=listdict) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_complex_item_null(send_request_json_response, products): - products_null = [products[0], None, products[2]] - request = array.build_get_complex_item_null_request() - assert products_null == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_complex_item_empty(send_request_json_response, products): - products_empty = [products[0], {}, products[2]] - - request = array.build_get_complex_item_empty_request() - assert products_empty == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_array_null(send_request): - request = array.build_get_array_null_request() - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_get_array_empty(send_request_json_response): - request = array.build_get_array_empty_request() - assert [] == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_array_item_null(send_request_json_response): - listlist2 = [["1", "2", "3"], None, ["7", "8", "9"]] - request = array.build_get_array_item_null_request() - assert listlist2 == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_array_item_empty(send_request_json_response): - listlist3 = [["1", "2", "3"], [], ["7", "8", "9"]] - request = array.build_get_array_item_empty_request() - assert listlist3 == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_dictionary_and_dictionary_item_null(send_request, send_request_json_response, listdict): - - request = array.build_get_dictionary_null_request() - assert (await send_request(request)).text() == '' - - listdict[1] = None - request = array.build_get_dictionary_item_null_request() - assert listdict == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_dictionary_and_dictionary_item_empty(send_request_json_response, listdict): - request = array.build_get_dictionary_empty_request() - assert [] == await send_request_json_response(request) - - listdict[1] = {} - request = array.build_get_dictionary_item_empty_request() - assert listdict == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_array_get_invalid(send_request_json_response): - request = array.build_get_invalid_request() - with pytest.raises(DecodeError): # raises a diff error than the sync version - await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_array_get_boolean_invalid_null(send_request_json_response): - request = array.build_get_boolean_invalid_null_request() - assert await send_request_json_response(request), [True, None == False] - -@pytest.mark.asyncio -async def test_array_get_boolean_invalid_string(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_boolean_invalid_string_request() - assert await send_request_json_response(request) == [True, "boolean", False] - -@pytest.mark.asyncio -async def test_array_get_int_invalid_null(send_request_json_response): - request = array.build_get_int_invalid_null_request() - assert await send_request_json_response(request), [1, None == 0] - -@pytest.mark.asyncio -async def test_array_get_int_invalid_string(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_int_invalid_string_request() - assert await send_request_json_response(request) == [1, "integer", 0] - -@pytest.mark.asyncio -async def test_array_get_long_invalid_null(send_request_json_response): - request = array.build_get_long_invalid_null_request() - assert await send_request_json_response(request), [1, None == 0] - -@pytest.mark.asyncio -async def test_array_get_long_invalid_string(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_long_invalid_string_request() - assert await send_request_json_response(request) == [1, "integer", 0] - -@pytest.mark.asyncio -async def test_array_get_float_invalid_null(send_request_json_response): - request = array.build_get_float_invalid_null_request() - assert await send_request_json_response(request), [0.0, None == -1.2e20] - -@pytest.mark.asyncio -async def test_array_get_float_invalid_string(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_float_invalid_string_request() - assert await send_request_json_response(request) == [1, "number", 0] - -@pytest.mark.asyncio -async def test_array_get_double_invalid_null(send_request_json_response): - request = array.build_get_double_invalid_null_request() - assert await send_request_json_response(request), [0.0, None == -1.2e20] - -@pytest.mark.asyncio -async def test_array_get_double_invalid_string(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_double_invalid_string_request() - assert await send_request_json_response(request) == [1, "number", 0] - -@pytest.mark.asyncio -async def test_array_get_string_with_invalid(send_request_json_response): - request = array.build_get_string_with_invalid_request() - assert await send_request_json_response(request), ["foo", "123" == "foo2"] - -@pytest.mark.asyncio -async def test_array_get_date_invalid_null(send_request_json_response): - request = array.build_get_date_invalid_null_request() - assert await send_request_json_response(request), [isodate.parse_date("2012-01-01"), None == isodate.parse_date("1776-07-04")] - -@pytest.mark.asyncio -async def test_array_get_date_invalid_chars(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_date_invalid_chars_request() - assert await send_request_json_response(request) == ["2011-03-22", "date"] - -@pytest.mark.asyncio -async def test_array_get_date_time_invalid_null(send_request_json_response): - request = array.build_get_date_time_invalid_null_request() - assert await send_request_json_response(request), [isodate.parse_datetime("2000-12-01T00:00:01Z") == None] - -@pytest.mark.asyncio -async def test_array_get_date_time_invalid_chars(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_date_time_invalid_chars_request() - assert await send_request_json_response(request) == ['2000-12-01t00:00:01z', 'date-time'] - -@pytest.mark.asyncio -async def test_array_get_base64_url(send_request_json_response, deserializer): - test_array = ['a string that gets encoded with base64url'.encode(), - 'test string'.encode(), - 'Lorem ipsum'.encode()] - request = array.build_get_base64_url_request() - response = await send_request_json_response(request) - assert [deserializer.deserialize_base64(s) for s in await send_request_json_response(request)] == test_array - -@pytest.mark.asyncio -async def test_array_enum_valid(send_request, send_request_json_response): - request = array.build_get_enum_valid_request() - response = await send_request_json_response(request) - assert response == ['foo1', 'foo2', 'foo3'] - request = array.build_put_enum_valid_request(json=response) - await send_request(request) - -@pytest.mark.asyncio -async def test_array_string_enum_valid(send_request, send_request_json_response): - request = array.build_get_string_enum_valid_request() - response = await send_request_json_response(request) - assert response == ['foo1', 'foo2', 'foo3'] - request = array.build_put_string_enum_valid_request(json=response) - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_binary.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_binary.py deleted file mode 100644 index 9228bcb6688..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_binary.py +++ /dev/null @@ -1,48 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -import json -from bodybinarylowlevel.aio import BinaryWithContentTypeApplicationJson -from bodybinarylowlevel.rest import upload - -@pytest.fixture -async def client(): - async with BinaryWithContentTypeApplicationJson() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -async def test_upload_file(send_request): - request = upload.build_file_request(content=json.dumps({"more": "cowbell"}), headers={"Content-Type": "application/json"}) - await send_request(request) - -async def test_upload_binary(send_request): - request = upload.build_binary_request(content=b"Hello, world!", headers={"Content-Type": "application/octet-stream"}) - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_bool.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_bool.py deleted file mode 100644 index 0b4874eeb2a..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_bool.py +++ /dev/null @@ -1,79 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from bodybooleanlowlevel.aio import AutoRestBoolTestService -from bodybooleanlowlevel.rest import bool -from async_generator import yield_, async_generator -import pytest -from azure.core.exceptions import DecodeError - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestBoolTestService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_model_get_true(send_request_json_response): - request = bool.build_get_true_request() - assert await send_request_json_response(request) == True - -@pytest.mark.asyncio -async def test_model_get_false(send_request_json_response): - request = bool.build_get_false_request() - assert not await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_model_get_null(send_request): - request = bool.build_get_null_request() - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_model_put_false(send_request): - request = bool.build_put_false_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_model_put_true(send_request): - request = bool.build_put_true_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_model_get_invalid(send_request): - request = bool.build_get_invalid_request() - with pytest.raises(DecodeError): - await send_request(request) # this behavior is diff from sync diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_byte.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_byte.py deleted file mode 100644 index 98ffff51c9e..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_byte.py +++ /dev/null @@ -1,72 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from bodybytelowlevel.aio import AutoRestSwaggerBATByteService -from bodybytelowlevel.rest import byte -from async_generator import yield_, async_generator -from base64 import b64encode, b64decode - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestSwaggerBATByteService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_non_ascii(send_request): - def deserialize_base64(attr): - padding = '=' * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace('-', '+').replace('_', '/') - return b64decode(encoded) - tests = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x0FB, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) - request = byte.build_put_non_ascii_request(json=b64encode(tests).decode()) - await send_request(request) - - request = byte.build_get_non_ascii_request() - assert tests == deserialize_base64((await send_request(request)).text()) - -@pytest.mark.asyncio -async def test_get_null(send_request): - request = byte.build_get_null_request() - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_get_empty(send_request): - request = byte.build_get_empty_request() - assert b'""' == (await send_request(request)).content # in convenience layer, we deserialize as bytearray specif - -@pytest.mark.asyncio -async def test_get_invalid(send_request): - request = byte.build_get_invalid_request() - assert (await send_request(request)).content == b'"::::SWAGGER::::"' diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_complex.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_complex.py deleted file mode 100644 index 90ffded07be..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_complex.py +++ /dev/null @@ -1,655 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from async_generator import yield_, async_generator -import pytest -import isodate -from datetime import datetime, timedelta, tzinfo -from bodycomplexlowlevel.aio import AutoRestComplexTestService -from bodycomplexlowlevel.rest import ( - basic, - array, - dictionary, - polymorphicrecursive, - polymorphism, - primitive, - readonlyproperty, - inheritance, -) -from azure.core.exceptions import HttpResponseError -from bodycomplexlowlevel._serialization import Serializer, Deserializer -from base64 import b64decode, b64encode - - -class UTC(tzinfo): - def utcoffset(self,dt): - return timedelta(hours=0,minutes=0) - - def tzname(self,dt): - return "Z" - - 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 send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@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(send_request, send_request_json_response): - # GET basic/valid - request = basic.build_get_valid_request() - basic_result = await send_request_json_response(request) - assert 2 == basic_result['id'] - assert "abc" == basic_result['name'] - assert "YELLOW" == basic_result['color'] - - # PUT basic/valid - json = { - "id": 2, - "name": "abc", - "color": "Magenta", - } - request = basic.build_put_valid_request(json=json) - await send_request(request) - json = { - "id": 2, - "name": "abc", - "color": "Magenta", - } - request = basic.build_put_valid_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_basic_get_empty(send_request, send_request_json_response): - # GET basic/empty - request = basic.build_get_empty_request() - basic_result = await send_request_json_response(request) - assert basic_result == {} - -@pytest.mark.asyncio -async def test_basic_get_null(send_request_json_response): - # GET basic/null - request = basic.build_get_null_request() - basic_result = await send_request_json_response(request) - assert basic_result['id'] is None - assert basic_result['name'] is None - -@pytest.mark.asyncio -async def test_basic_get_not_provided(send_request): - # GET basic/notprovided - request = basic.build_get_not_provided_request() - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_basic_get_invalid(send_request_json_response): - # GET basic/invalid - request = basic.build_get_invalid_request() - basic_result = await send_request_json_response(request) - # it's deserialized as invalid bc the id is not a number - # with LLC, we don't care thought - 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(send_request, send_request_json_response): - # GET primitive/integer - request = primitive.build_get_int_request() - int_result = await send_request_json_response(request) - assert -1 == int_result['field1'] - assert 2 == int_result['field2'] - - # PUT primitive/integer - int_request = {'field1':-1, 'field2':2} - request = primitive.build_put_int_request(json=int_request) - await send_request(request) - -@pytest.mark.asyncio -async def test_primitive_get_and_put_long(send_request, send_request_json_response): - # GET primitive/long - request = primitive.build_get_long_request() - long_result = await send_request_json_response(request) - assert 1099511627775 == long_result['field1'] - assert -999511627788 == long_result['field2'] - - # PUT primitive/long - json = {'field1':1099511627775, 'field2':-999511627788} - request = primitive.build_put_long_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_primitive_get_and_put_float(send_request, send_request_json_response): - # GET primitive/float - request = primitive.build_get_float_request() - float_result = await send_request_json_response(request) - assert 1.05 == float_result['field1'] - assert -0.003 == float_result['field2'] - - # PUT primitive/float - json = { - "field1": 1.05, - "field2": -0.003 - } - request = primitive.build_put_float_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_primitive_get_and_put_double(send_request, send_request_json_response): - # GET primitive/double - request = primitive.build_get_double_request() - double_result = await send_request_json_response(request) - 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 - json = { - "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 - } - request = primitive.build_put_double_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_primitive_get_and_put_bool(send_request, send_request_json_response): - # GET primitive/bool - request = primitive.build_get_bool_request() - bool_result = await send_request_json_response(request) - assert bool_result['field_true'] - assert not bool_result['field_false'] - - # PUT primitive/bool - json = { - "field_true": True, - "field_false": False - } - request = primitive.build_put_bool_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_primitive_get_and_put_string(send_request, send_request_json_response): - # GET primitive/string - request = primitive.build_get_string_request() - string_result = await send_request_json_response(request) - assert "goodrequest" == string_result['field'] - assert "" == string_result['empty'] - assert string_result['null'] is None - - # PUT primitive/string - json = { - "null": None, - "empty": "", - "field": "goodrequest" - } - request = primitive.build_put_string_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_primitive_get_and_put_date(send_request, send_request_json_response): - # GET primitive/date - request = primitive.build_get_date_request() - date_result = await send_request_json_response(request) - 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']) - - json = { - "field": '0001-01-01', - "leap": '2016-02-29' - } - request = primitive.build_put_date_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_primitive_get_and_put_date_time(send_request, send_request_json_response, min_date): - # GET primitive/datetime - request = primitive.build_get_date_time_request() - datetime_result = await send_request_json_response(request) - - assert min_date == Deserializer.deserialize_iso(datetime_result['field']) - - json = { - "field": "0001-01-01T00:00:00Z", - "now": "2015-05-18T18:38:00Z" - } - request = primitive.build_put_date_time_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_primitive_get_and_put_date_time_rfc1123(send_request, send_request_json_response): - # GET primitive/datetimerfc1123 - request = primitive.build_get_date_time_rfc1123_request() - datetimerfc1123_result = await send_request_json_response(request) - - # 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']) - - # we can still model year 1 though with the latest msrest update - json = { - "field": Serializer.serialize_rfc(isodate.parse_datetime("0001-01-01T00:00:00Z")), - "now": Serializer.serialize_rfc(isodate.parse_datetime("2015-05-18T11:38:00Z")) - } - request = primitive.build_put_date_time_rfc1123_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_primitive_get_and_put_duration(send_request, send_request_json_response): - # GET primitive/duration - expected = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) - request = primitive.build_get_duration_request() - duration_result = await send_request_json_response(request) - assert expected == Deserializer.deserialize_duration(duration_result['field']) - - request = primitive.build_put_duration_request(json={"field": Serializer.serialize_duration(expected)}) - await send_request(request) - -@pytest.mark.asyncio -async def test_primitive_get_and_put_byte(send_request, send_request_json_response): - # GET primitive/byte - request = primitive.build_get_byte_request() - byte_result = await send_request_json_response(request) - valid_bytes = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x000, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) - assert valid_bytes == bytearray(b64decode(byte_result['field'])) - - # PUT primitive/byte - request = primitive.build_put_byte_request(json={"field": b64encode(valid_bytes).decode()}) - await send_request(request) - -# COMPLEX TYPE WITH READ ONLY PROPERTIES - -@pytest.mark.asyncio -async def test_readonlyproperty_get_and_put_valid(send_request, send_request_json_response): - # GET readonly/valid - valid_obj = {"size": 2, 'id': '1234'} - request = readonlyproperty.build_get_valid_request() - readonly_result = await send_request_json_response(request) - assert readonly_result == valid_obj - - # PUT readonly/valid - request = readonlyproperty.build_put_valid_request(json=2) - assert (await send_request(request)).text() == '' - -# COMPLEX TYPE WITH ARRAY PROPERTIES - -@pytest.mark.asyncio -async def test_array_get_and_put_valid(send_request, send_request_json_response): - # GET array/valid - request = array.build_get_valid_request() - array_result = await send_request_json_response(request) - 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 - - # PUT array/valid - request = array.build_put_valid_request(json={"array": array_value}) - await send_request(request) - -@pytest.mark.asyncio -async def test_array_get_and_put_empty(send_request, send_request_json_response): - - # GET array/empty - request = array.build_get_empty_request() - array_result = await send_request_json_response(request) - assert 0 == len(array_result['array']) - - # PUT array/empty - request = array.build_put_empty_request(json={"array": []}) - await send_request(request) - -@pytest.mark.asyncio -async def test_array_get_not_provided(send_request_json_response): - # Get array/notprovided - request = array.build_get_not_provided_request() - assert await send_request_json_response(request) == {} - -# COMPLEX TYPE WITH DICTIONARY PROPERTIES - -@pytest.mark.asyncio -async def test_dictionary_get_and_put_valid(send_request, send_request_json_response): - # GET dictionary/valid - request = dictionary.build_get_valid_request() - dict_result = await send_request_json_response(request) - assert 5 == len(dict_result['defaultProgram']) - - dict_val = {'txt':'notepad', 'bmp':'mspaint', 'xls':'excel', 'exe':'', '':None} - assert dict_val == dict_result['defaultProgram'] - - # PUT dictionary/valid - request = dictionary.build_put_valid_request(json={"defaultProgram": dict_val}) - await send_request(request) - -@pytest.mark.asyncio -async def test_dictionary_get_and_put_empty(send_request, send_request_json_response): - # GET dictionary/empty - request = dictionary.build_get_empty_request() - dict_result = await send_request_json_response(request) - assert 0 == len(dict_result['defaultProgram']) - - # PUT dictionary/empty - request = dictionary.build_put_empty_request(json={"defaultProgram": {}}) - await send_request(request) - -@pytest.mark.asyncio -async def test_dictionary_get_and_null(send_request_json_response): - # GET dictionary/null - request = dictionary.build_get_null_request() - dictionary_result = await send_request_json_response(request) - assert dictionary_result['defaultProgram'] is None - -@pytest.mark.asyncio -async def test_dictionary_get_not_provided(send_request_json_response): - # GET dictionary/notprovided - request = dictionary.build_get_not_provided_request() - assert await send_request_json_response(request) == {} - - -# COMPLEX TYPES THAT INVOLVE INHERITANCE - -@pytest.mark.asyncio -async def test_inheritance_get_and_put_valid(send_request, send_request_json_response): - # GET inheritance/valid - request = inheritance.build_get_valid_request() - inheritance_result = await send_request_json_response(request) - 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 - json = { - 'id': 2, - 'name': "Siameeee", - 'color': "green", - 'breed': "persian", - 'hates': [{"id": 1, "name": "Potato", "food": "tomato"}, - {"id": -1, "name": "Tomato", "food": "french fries"}] - } - request = inheritance.build_put_valid_request(json=json) - await send_request(request) - -# COMPLEX TYPES THAT INVOLVE POLYMORPHISM - -@pytest.mark.asyncio -async def test_get_composed_with_discriminator(send_request_json_response): - request = polymorphism.build_get_composed_with_discriminator_request() - result = await send_request_json_response(request) - assert result['sampleSalmon']['fish.type'] == "DotSalmon" - -@pytest.mark.asyncio -async def test_get_composed_without_discriminator(send_request_json_response): - request = polymorphism.build_get_composed_without_discriminator_request() - result = await send_request_json_response(request) - with pytest.raises(KeyError): - result['sampleSalmon']['fish.type'] # shouldn't have a discriminator - -@pytest.mark.asyncio -async def test_polymorphism_get_and_put_valid(send_request, send_request_json_response): - # GET polymorphism/valid - request = polymorphism.build_get_valid_request() - result = await send_request_json_response(request) - 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 - - - # PUT polymorphism/valid - json = { - "fishtype": "salmon", - "species": "king", - "length": 1.0, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20.0, - "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "age": 105, - "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - }, - { - "fishtype": "goblin", - "species": "scary", - "length": 30.0, - "age": 1, - "birthday": "2015-08-08T00:00:00.000Z", - "jawsize": 5, - "color": "pinkish-gray" - } - ], - "location": "alaska", - "iswild": True - } - request = polymorphism.build_put_valid_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_polymorphism_put_valid_missing_required(send_request): - json = { - "fishtype": "salmon", - "species": "king", - "length": 1.0, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20.0, - "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "age": 105, - "picture": "//////4=" - } - ], - "location": "alaska", - "iswild": True - } - - request = polymorphism.build_put_valid_missing_required_request(json=json) - - # in convenience layer, this raises a ValidationError (when generated with client side validation) - with pytest.raises(HttpResponseError) as e: - await send_request(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(send_request, send_request_json_response): - # GET polymorphicrecursive/valid - request = polymorphicrecursive.build_get_valid_request() - result = await send_request_json_response(request) - 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" - - json = { - "fishtype": "salmon", - "species": "king", - "length": 1.0, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20.0, - "siblings": [ - { - "fishtype": "salmon", - "species": "coho", - "length": 2.0, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20.0, - "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "age": 105, - "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } - ], - "location": "atlantic", - "iswild": True - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "siblings": [], - "age": 105, - "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } - ], - "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "siblings": [], - "age": 105, - "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } - ], - "location": "alaska", - "iswild": True - } - - # PUT polymorphicrecursive/valid - request = polymorphicrecursive.build_put_valid_request(json=json) - await send_request(request) - - -# Complex types that uses additional properties and polymorphism -@pytest.mark.asyncio -async def test_polymorphism_get_and_put_complicated(send_request, send_request_json_response): - request = polymorphism.build_get_complicated_request() - response = await send_request_json_response(request) - request = polymorphism.build_put_complicated_request(json=response) - await send_request(request) - -# Complex types that uses missing discriminator - -@pytest.mark.asyncio -async def test_polymorphism_get_and_put_missing_discriminator(send_request, send_request_json_response): - json = { - "fishtype": "salmon", - "species": "king", - "length": 1.0, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20.0, - "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "age": 105, - "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - }, - { - "fishtype": "goblin", - "species": "scary", - "length": 30.0, - "age": 1, - "birthday": "2015-08-08T00:00:00.000Z", - "jawsize": 5, - "color": "pinkish-gray" - } - ], - "location": "alaska", - "iswild": True - } - # Not raise is enough of a test - request = polymorphism.build_put_missing_discriminator_request(json=json) - await send_request(request) - - # Dot syntax - request = polymorphism.build_get_dot_syntax_request() - dot_salmon = await send_request_json_response(request) - assert dot_salmon['fish.type'] == "DotSalmon" - assert dot_salmon['location'] == "sweden" - -@pytest.mark.asyncio -async def test_pass_in_api_version(client): - assert client._config.api_version == "2016-02-29" - async with AutoRestComplexTestService(api_version="2021-10-01") as client: - assert client._config.api_version == "2021-10-01" diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_config.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_config.py deleted file mode 100644 index b1da088fb94..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_config.py +++ /dev/null @@ -1,45 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from azure.core.pipeline.policies import HttpLoggingPolicy -from bodystringlowlevel.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"} - ) - 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"}) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_constants.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_constants.py deleted file mode 100644 index 83858ff71d8..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_constants.py +++ /dev/null @@ -1,59 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from constantslowlevel.aio import AutoRestSwaggerConstantService -from constantslowlevel.rest import contants - -@pytest.fixture -async def client(): - async with AutoRestSwaggerConstantService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_put_client_constants(client, send_request): - assert client._config.header_constant == True - assert client._config.query_constant == 100 - assert client._config.path_constant == "path" - - request = contants.build_put_client_constants_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_put_client_constants_override(): - async 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" diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_content_type.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_content_type.py deleted file mode 100644 index b5d5924f132..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_content_type.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import io -import pytest -from mediatypeslowlevel.aio import MediaTypesClient -from mediatypeslowlevel.rest import * -from async_generator import yield_, async_generator - -@pytest.mark.asyncio -async def test_stream_unread_until_send_request(): - class FakeStream: - def __init__(self): - self.call_count = 0 - - @async_generator - async def streaming_body(self, data): - self.call_count += 1 - await yield_(data) - - fake_stream = FakeStream() - request = build_analyze_body_request(content=fake_stream.streaming_body(b"PDF")) - assert not request.headers.get("Content-Type") - assert fake_stream.call_count == 0 - await MediaTypesClient().send_request(request) - assert fake_stream.call_count == 1 diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_date.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_date.py deleted file mode 100644 index 94fb7608039..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_date.py +++ /dev/null @@ -1,94 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import isodate -import datetime -from async_generator import yield_, async_generator - -from bodydatelowlevel.aio import AutoRestDateTestService -from bodydatelowlevel.rest import date - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestDateTestService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_model_get_and_put_max_date(send_request, send_request_json_response): - max_date = isodate.parse_date("9999-12-31T23:59:59.999999Z") - request = date.build_put_max_date_request(json=str(max_date)) - await send_request(request) - - request = date.build_get_max_date_request() - assert max_date == isodate.parse_date(await send_request_json_response(request)) - -@pytest.mark.asyncio -async def test_model_get_and_put_min_date(send_request, send_request_json_response): - min_date = isodate.parse_date("0001-01-01T00:00:00Z") - request = date.build_put_min_date_request(json=str(min_date)) - await send_request(request) - - request = date.build_get_min_date_request() - assert min_date == isodate.parse_date(await send_request_json_response(request)) - -@pytest.mark.asyncio -async def test_model_get_null(send_request): - request = date.build_get_null_request() - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_model_get_invalid_date(send_request_json_response): - request = date.build_get_invalid_date_request() - assert datetime.date(2001, 1, 1) == isodate.parse_date(await send_request_json_response(request)) - -@pytest.mark.asyncio -async def test_model_get_overflow_date(send_request_json_response): - request = date.build_get_overflow_date_request() - with pytest.raises(ValueError) as ex: - isodate.parse_date(await send_request_json_response(request)) - assert "day is out of range for month" in str(ex.value) - -@pytest.mark.asyncio -async def test_model_get_underflow_date(send_request_json_response): - request = date.build_get_underflow_date_request() - with pytest.raises(ValueError) as ex: - isodate.parse_date(await send_request_json_response(request)) - assert "year 0 is out of range" in str(ex.value) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_datetime.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_datetime.py deleted file mode 100644 index fdb24ec63f5..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_datetime.py +++ /dev/null @@ -1,174 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import isodate -from async_generator import yield_, async_generator - -from azure.core.exceptions import DeserializationError, SerializationError - -from bodydatetimelowlevel.aio import AutoRestDateTimeTestService -from bodydatetimelowlevel.rest import datetime -from bodydatetimelowlevel._serialization import Serializer, Deserializer - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestDateTimeTestService() as client: - await yield_(client) -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.fixture -def serializer(): - return Serializer() - -@pytest.fixture -def deserializer(): - return Deserializer - -@pytest.fixture -def get_deserialized_iso(send_request_json_response, deserializer): - async def _get_deserialized_iso(request): - return deserializer.deserialize_iso(await send_request_json_response(request)) - return _get_deserialized_iso - -@pytest.fixture -def get_serialized_iso(serializer): - def _get_serialized_iso(date): - return serializer.serialize_iso(date) - return _get_serialized_iso - -@pytest.mark.asyncio -async def test_utc_max_date_time(send_request, get_serialized_iso, get_deserialized_iso): - max_date = isodate.parse_datetime("9999-12-31T23:59:59.999Z") - request = datetime.build_get_utc_lowercase_max_date_time_request() - assert max_date == await get_deserialized_iso(request) - - request = datetime.build_get_utc_uppercase_max_date_time_request() - assert await get_deserialized_iso(request) == max_date - - request = datetime.build_put_utc_max_date_time_request(json=get_serialized_iso(max_date)) - await send_request(request) - -@pytest.mark.asyncio -async def test_utc_max_date_time_7digits(send_request, get_serialized_iso, get_deserialized_iso): - max_date = isodate.parse_datetime("9999-12-31T23:59:59.999999Z") - request = datetime.build_get_utc_uppercase_max_date_time7_digits_request() - assert await get_deserialized_iso(request) == max_date - - request = datetime.build_put_utc_max_date_time7_digits_request(json=get_serialized_iso(max_date)) - with pytest.raises(Exception): - # Python doesn't support 7 digits - await send_request(request) - -@pytest.mark.asyncio -async def test_get_utc_min_date_time(send_request, get_serialized_iso, get_deserialized_iso): - min_date = isodate.parse_datetime("0001-01-01T00:00:00Z") - request = datetime.build_get_utc_min_date_time_request() - assert await get_deserialized_iso(request) == min_date - - request = datetime.build_put_utc_min_date_time_request(json=get_serialized_iso(min_date)) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_local_negative_offset_min_date_time(send_request, send_request_json_response, get_serialized_iso): - request = datetime.build_get_local_negative_offset_min_date_time_request() - assert '0001-01-01T00:00:00-14:00' == await send_request_json_response(request) - - request = datetime.build_put_local_negative_offset_min_date_time_request(json=get_serialized_iso(isodate.parse_datetime("0001-01-01T00:00:00-14:00"))) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_local_no_offset_min_date_time(get_deserialized_iso): - local_no_offset_min_date_time = isodate.parse_datetime("0001-01-01T00:00:00") - request = datetime.build_get_local_no_offset_min_date_time_request() - assert await get_deserialized_iso(request) == local_no_offset_min_date_time - -@pytest.mark.asyncio -async def test_get_local_negative_offset_lowercase_max_date_time(send_request_json_response): - request = datetime.build_get_local_negative_offset_lowercase_max_date_time_request() - assert await send_request_json_response(request) == "9999-12-31t23:59:59.999-14:00" - -@pytest.mark.asyncio -async def test_get_local_negative_offset_uppercase_max_date_time(send_request_json_response): - request = datetime.build_get_local_negative_offset_uppercase_max_date_time_request() - assert await send_request_json_response(request) == "9999-12-31T23:59:59.999-14:00" - -@pytest.mark.asyncio -async def test_local_positive_offset_min_date_time(send_request_json_response, get_serialized_iso): - request = datetime.build_get_local_positive_offset_min_date_time_request() - assert await send_request_json_response(request) == "0001-01-01T00:00:00+14:00" - - with pytest.raises(SerializationError): - datetime.build_put_local_positive_offset_min_date_time_request(json=get_serialized_iso(isodate.parse_datetime("0001-01-01T00:00:00+14:00"))) - - -@pytest.mark.asyncio -async def test_local_positive_offset_max_date_time(send_request_json_response, send_request, get_serialized_iso): - request = datetime.build_get_local_positive_offset_lowercase_max_date_time_request() - assert await send_request_json_response(request) == "9999-12-31t23:59:59.999+14:00" - - request = datetime.build_get_local_positive_offset_uppercase_max_date_time_request() - assert await send_request_json_response(request) == "9999-12-31T23:59:59.999+14:00" - - request = datetime.build_put_local_positive_offset_max_date_time_request(json=get_serialized_iso(isodate.parse_datetime("9999-12-31T23:59:59.999999+14:00"))) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_null(send_request, get_serialized_iso, get_deserialized_iso): - request = datetime.build_get_null_request() - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_get_overflow(send_request_json_response): - request = datetime.build_get_overflow_request() - assert await send_request_json_response(request) == "9999-12-31T23:59:59.999-14:00" - -@pytest.mark.asyncio -async def test_get_invalid(send_request_json_response): - request = datetime.build_get_invalid_request() - assert await send_request_json_response(request) == "201O-18-90D00:89:56.9AX" - -@pytest.mark.asyncio -async def test_get_underflow(send_request_json_response): - request = datetime.build_get_underflow_request() - assert await send_request_json_response(request) == "0000-00-00T00:00:00.000+00:00" - -@pytest.mark.asyncio -async def test_put_local_negative_offset_max_date_time(get_serialized_iso): - with pytest.raises(SerializationError): - datetime.build_put_local_negative_offset_max_date_time_request(json=get_serialized_iso(isodate.parse_datetime("9999-12-31T23:59:59.999999-14:00"))) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_datetime_rfc.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_datetime_rfc.py deleted file mode 100644 index 3ac2e4a9ca8..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_datetime_rfc.py +++ /dev/null @@ -1,99 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import isodate -from async_generator import yield_, async_generator - -from bodydatetimerfc1123lowlevel.aio import AutoRestRFC1123DateTimeTestService -from bodydatetimerfc1123lowlevel.rest import datetimerfc1123 -from bodydatetimerfc1123lowlevel._serialization import Serializer - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestRFC1123DateTimeTestService() as client: - await yield_(client) - - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.fixture -def serializer(): - return Serializer() - - -@pytest.mark.asyncio -async def test_get_null(send_request): - request = datetimerfc1123.build_get_null_request() - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_get_invalid(send_request_json_response): - request = datetimerfc1123.build_get_invalid_request() - assert "Tue, 01 Dec 2000 00:00:0A ABC" == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_underflow(send_request_json_response): - request = datetimerfc1123.build_get_underflow_request() - assert "Tue, 00 Jan 0000 00:00:00 GMT" == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_overflow(send_request_json_response): - request = datetimerfc1123.build_get_overflow_request() - assert "Sat, 1 Jan 10000 00:00:00 GMT" == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_utc_max_date_time(send_request, serializer): - max_date = isodate.parse_datetime("9999-12-31T23:59:59.999999Z") - - request = datetimerfc1123.build_get_utc_lowercase_max_date_time_request() - await send_request(request) - - request = datetimerfc1123.build_get_utc_uppercase_max_date_time_request() - await send_request(request) - - request = datetimerfc1123.build_put_utc_max_date_time_request(json=serializer.serialize_rfc(max_date)) - await send_request(request) - -@pytest.mark.asyncio -async def test_utc_min_date_time(send_request, serializer): - min_date = isodate.parse_datetime("0001-01-01T00:00:00Z") - request = datetimerfc1123.build_get_utc_min_date_time_request() - await send_request(request) - - request = datetimerfc1123.build_put_utc_min_date_time_request(json=serializer.serialize_rfc(min_date)) - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_dictionary.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_dictionary.py deleted file mode 100644 index 1e5239705ed..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_dictionary.py +++ /dev/null @@ -1,427 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import isodate -from datetime import timedelta -from bodydictionarylowlevel.rest import dictionary -from bodydictionarylowlevel.aio import AutoRestSwaggerBATDictionaryService -from bodydictionarylowlevel._serialization import Serializer, Deserializer -from azure.core.exceptions import DecodeError -from async_generator import yield_, async_generator - - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestSwaggerBATDictionaryService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.fixture -def get_deserialized_dict(send_request_json_response): - async def _get_deserialized_dict(request, deserialize_value_callable): - json_response = await send_request_json_response(request) - return { - str(idx): deserialize_value_callable(json_response[key]) if json_response[key] else None - for idx, key in enumerate(json_response.keys()) - } - return _get_deserialized_dict - -@pytest.fixture -def get_serialized_dict(): - def _get_serialized_dict(dict, serialize_value_callable): - return { - k: serialize_value_callable(v) for k, v in dict.items() - } - return _get_serialized_dict - -@pytest.fixture -def serializer(): - return Serializer() - -@pytest.fixture -def deserializer(): - return Deserializer() - - -@pytest.fixture -@pytest.mark.asyncio -async 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} - -# Primitive types -@pytest.mark.asyncio -async def test_boolean_tfft(send_request, send_request_json_response): - tfft = {"0":True, "1":False, "2":False, "3":True} - request = dictionary.build_get_boolean_tfft_request() - assert tfft == await send_request_json_response(request) - - request = dictionary.build_put_boolean_tfft_request(json=tfft) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_boolean_invalid(send_request_json_response): - invalid_null_dict = {"0":True, "1":None, "2":False} - request = dictionary.build_get_boolean_invalid_null_request() - assert invalid_null_dict == await send_request_json_response(request) - - request = dictionary.build_get_boolean_invalid_string_request() - assert {"0": True, "1": "boolean", "2": False} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_integer_valid(send_request, send_request_json_response): - int_valid = {"0":1, "1":-1, "2":3, "3":300} - request = dictionary.build_get_integer_valid_request() - assert int_valid == await send_request_json_response(request) - - request = dictionary.build_put_integer_valid_request(json=int_valid) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_int_invalid(send_request_json_response): - int_null_dict = {"0":1, "1":None, "2":0} - request = dictionary.build_get_int_invalid_null_request() - assert int_null_dict == await send_request_json_response(request) - - request = dictionary.build_get_int_invalid_string_request() - assert {"0": 1, "1": "integer", "2": 0} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_long_valid(send_request, send_request_json_response): - long_valid = {"0":1, "1":-1, "2":3, "3":300} - request = dictionary.build_get_long_valid_request() - assert long_valid == await send_request_json_response(request) - - request = dictionary.build_put_long_valid_request(json=long_valid) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_long_invalid(send_request_json_response): - long_null_dict = {"0":1, "1":None, "2":0} - request = dictionary.build_get_long_invalid_null_request() - assert long_null_dict == await send_request_json_response(request) - - request = dictionary.build_get_long_invalid_string_request() - assert {"0": 1, "1": "integer", "2": 0} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_float_valid(send_request, send_request_json_response): - float_valid = {"0":0, "1":-0.01, "2":-1.2e20} - request = dictionary.build_get_float_valid_request() - assert float_valid == await send_request_json_response(request) - - request = dictionary.build_put_float_valid_request(json=float_valid) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_float_invalid(send_request_json_response): - float_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - request = dictionary.build_get_float_invalid_null_request() - assert float_null_dict == await send_request_json_response(request) - - request = dictionary.build_get_float_invalid_string_request() - assert {"0": 1, "1": "number", "2": 0} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_double_valid(send_request, send_request_json_response): - double_valid = {"0":0, "1":-0.01, "2":-1.2e20} - request = dictionary.build_get_double_valid_request() - assert double_valid == await send_request_json_response(request) - - request = dictionary.build_put_double_valid_request(json=double_valid) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_double_invalid(send_request_json_response): - double_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - request = dictionary.build_get_double_invalid_null_request() - assert double_null_dict == await send_request_json_response(request) - - request = dictionary.build_get_double_invalid_string_request() - assert {"0": 1, "1": "number", "2": 0} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_string_valid(send_request, send_request_json_response): - string_valid = {"0":"foo1", "1":"foo2", "2":"foo3"} - request = dictionary.build_get_string_valid_request() - assert string_valid == await send_request_json_response(request) - - request = dictionary.build_put_string_valid_request(json=string_valid) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_string_with_null_and_invalid(send_request_json_response): - string_null_dict = {"0":"foo", "1":None, "2":"foo2"} - string_invalid_dict = {"0":"foo", "1":123, "2":"foo2"} # in llc, we don't know we should serialize this whole thing as string, so serializes 123 as number - request = dictionary.build_get_string_with_null_request() - assert string_null_dict == await send_request_json_response(request) - request = dictionary.build_get_string_with_invalid_request() - assert string_invalid_dict == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_date_valid(send_request, get_serialized_dict, get_deserialized_dict, serializer, deserializer): - 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} - - request = dictionary.build_get_date_valid_request() - assert await get_deserialized_dict(request, deserializer.deserialize_date) == valid_date_dict - - request = dictionary.build_put_date_valid_request(json=get_serialized_dict(valid_date_dict, serializer.serialize_date)) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_date_invalid(send_request_json_response, deserializer, get_deserialized_dict): - date_null_dict = {"0":isodate.parse_date("2012-01-01"), - "1":None, - "2":isodate.parse_date("1776-07-04")} - request = dictionary.build_get_date_invalid_null_request() - assert date_null_dict == await get_deserialized_dict(request, deserializer.deserialize_date) - - request = dictionary.build_get_date_invalid_chars_request() - assert {"0": "2011-03-22", "1": "date"} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_date_time_valid(send_request, get_deserialized_dict, get_serialized_dict, serializer, deserializer): - 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} - - request = dictionary.build_get_date_time_valid_request() - assert valid_datetime_dict == await get_deserialized_dict(request, deserializer.deserialize_iso) - - request = dictionary.build_put_date_time_valid_request( - json=get_serialized_dict(valid_datetime_dict, serializer.serialize_iso) - ) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_date_time_invalid(send_request_json_response, deserializer, get_deserialized_dict): - datetime_null_dict = {"0":isodate.parse_datetime("2000-12-01T00:00:01Z"), "1":None} - request = dictionary.build_get_date_time_invalid_null_request() - assert datetime_null_dict == await get_deserialized_dict(request, deserializer.deserialize_iso) - - request = dictionary.build_get_date_time_invalid_chars_request() - assert {"0": "2000-12-01t00:00:01z", "1": "date-time"} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_date_time_rfc1123_valid(send_request, get_deserialized_dict, get_serialized_dict, serializer, deserializer): - 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} - - request = dictionary.build_get_date_time_rfc1123_valid_request() - assert valid_rfc_dict == await get_deserialized_dict(request, deserializer.deserialize_rfc) - - request = dictionary.build_put_date_time_rfc1123_valid_request(json=get_serialized_dict(valid_rfc_dict, serializer.serialize_rfc)) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_duration_valid(send_request, serializer, deserializer, get_deserialized_dict, get_serialized_dict): - 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} - - request = dictionary.build_get_duration_valid_request() - assert valid_duration_dict == await get_deserialized_dict(request, deserializer.deserialize_duration) - - request = dictionary.build_put_duration_valid_request(json=get_serialized_dict(valid_duration_dict, serializer.serialize_duration)) - await send_request(request) - -@pytest.mark.asyncio -async def test_bytes_valid(send_request, serializer, deserializer, get_serialized_dict, get_deserialized_dict): - 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} - request = dictionary.build_put_byte_valid_request(json=get_serialized_dict(bytes_valid, serializer.serialize_bytearray)) - await send_request(request) - - request = dictionary.build_get_byte_valid_request() - assert bytes_valid == await get_deserialized_dict(request, deserializer.deserialize_bytearray) - -@pytest.mark.asyncio -async def test_get_byte_invalid_null(deserializer, get_deserialized_dict): - bytes4 = bytearray([0x0AB, 0x0AC, 0x0AD]) - bytes_null = {"0":bytes4, "1":None} - request = dictionary.build_get_byte_invalid_null_request() - assert bytes_null == await get_deserialized_dict(request, deserializer.deserialize_bytearray) -@pytest.mark.asyncio -async def test_get_base64_url(deserializer, get_deserialized_dict): - test_dict = {'0': 'a string that gets encoded with base64url'.encode(), - '1': 'test string'.encode(), - '2': 'Lorem ipsum'.encode()} - request = dictionary.build_get_base64_url_request() - assert test_dict == await get_deserialized_dict(request, deserializer.deserialize_base64) - -# Basic dictionary parsing -@pytest.mark.asyncio -async def test_empty(send_request, send_request_json_response): - - request = dictionary.build_get_empty_request() - assert {} == await send_request_json_response(request) - - request = dictionary.build_put_empty_request(json={}) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_null_and_invalid(send_request, send_request_json_response): - - request = dictionary.build_get_null_request() - assert (await send_request(request)).text() == '' - - request = dictionary.build_get_invalid_request() - with pytest.raises(DecodeError): - await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_null_key_and_value(send_request, send_request_json_response): - # {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. - request = dictionary.build_get_null_key_request() - with pytest.raises(DecodeError): - await send_request_json_response(request) - - request = dictionary.build_get_null_value_request() - assert {"key1":None} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_empty_string_key(send_request_json_response): - request = dictionary.build_get_empty_string_key_request() - assert {"":"val1"} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_complex_valid(send_request, send_request_json_response, test_dict): - - request = dictionary.build_put_complex_valid_request(json=test_dict) - await send_request(request) - - request = dictionary.build_get_complex_valid_request() - assert test_dict == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_array_valid(send_request, send_request_json_response): - list_dict = {"0":["1","2","3"], "1":["4","5","6"], "2":["7","8","9"]} - - request = dictionary.build_put_array_valid_request(json=list_dict) - await send_request(request) - - request = dictionary.build_get_array_valid_request() - assert list_dict == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_dictionary_valid(send_request, send_request_json_response): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{"4":"four","5":"five","6":"six"}, - "2":{"7":"seven","8":"eight","9":"nine"}} - - request = dictionary.build_put_dictionary_valid_request(json=dict_dict) - await send_request(request) - - request = dictionary.build_get_dictionary_valid_request() - assert dict_dict == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_complex_null_and_empty(send_request, send_request_json_response): - - request = dictionary.build_get_complex_null_request() - assert (await send_request(request)).text() == '' - - request = dictionary.build_get_complex_empty_request() - assert {} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_complex_item_null_and_empty(send_request_json_response, test_dict): - test_dict_null = {"0":test_dict["0"], "1":None, "2":test_dict["2"]} - - request = dictionary.build_get_complex_item_null_request() - assert test_dict_null == await send_request_json_response(request) - - test_dict_empty = {"0":test_dict["0"], "1": {}, "2":test_dict["2"]} - - request = dictionary.build_get_complex_item_empty_request() - assert await send_request_json_response(request) == test_dict_empty - -@pytest.mark.asyncio -async def test_get_array_empty(send_request, send_request_json_response): - request = dictionary.build_get_array_null_request() - assert (await send_request(request)).text() == '' - - request = dictionary.build_get_array_empty_request() - assert {} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_array_item_null_and_empty(send_request_json_response): - list_dict = {"0":["1","2","3"], "1":None, "2":["7","8","9"]} - request = dictionary.build_get_array_item_null_request() - assert list_dict == await send_request_json_response(request) - - # in convenience layer, we deserialize as {[str]}. Since we don't have that in llc, the value for "1" will be None, not an empty list - request = dictionary.build_get_array_item_empty_request() - list_dict = {"0":["1","2","3"], "1":[], "2":["7","8","9"]} - assert list_dict == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_dictionary_null_and_empty(send_request, send_request_json_response): - request = dictionary.build_get_dictionary_null_request() - assert (await send_request(request)).text() == '' - - request = dictionary.build_get_dictionary_empty_request() - assert {} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_get_dictionary_item_null_and_empty(send_request, send_request_json_response): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":None, - "2":{"7":"seven","8":"eight","9":"nine"}} - request = dictionary.build_get_dictionary_item_null_request() - assert dict_dict == await send_request_json_response(request) - - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{}, - "2":{"7":"seven","8":"eight","9":"nine"}} - request = dictionary.build_get_dictionary_item_empty_request() - assert dict_dict == await send_request_json_response(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_duration.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_duration.py deleted file mode 100644 index 914e8feecc4..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_duration.py +++ /dev/null @@ -1,69 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from datetime import timedelta -from async_generator import yield_, async_generator -import isodate - -from bodydurationlowlevel.aio import AutoRestDurationTestService -from bodydurationlowlevel.rest import duration - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestDurationTestService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_get_null_and_invalid(send_request, send_request_json_response): - request = duration.build_get_null_request() - assert (await send_request(request)).text() == '' - - request = duration.build_get_invalid_request() - with pytest.raises(isodate.ISO8601Error): - isodate.parse_duration(await send_request_json_response(request)) - -@pytest.mark.asyncio -async def test_positive_duration(send_request, send_request_json_response): - request = duration.build_get_positive_duration_request() - assert isodate.duration.Duration(4, 45005, 0, years=3, months=6) == isodate.parse_duration(await send_request_json_response(request)) - - request = duration.build_put_positive_duration_request(json=isodate.duration_isoformat(timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11))) - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_error_with_secrets.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_error_with_secrets.py deleted file mode 100644 index 34fa988c23e..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_error_with_secrets.py +++ /dev/null @@ -1,59 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from errorwithsecretslowlevel.aio import ErrorWithSecrets -from errorwithsecretslowlevel import rest -from azure.core.exceptions import HttpResponseError - -@pytest.fixture -async def client(): - async with ErrorWithSecrets() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_create_secret(send_request): - request = rest.build_create_secret_request( - headers={"authorization": "SharedKey 1c88a67921784300a462b2cb61da2339"}, - params={"key": "1c88a67921784300a462b2cb61da2339"}, - json={ "key": "1c88a67921784300a462b2cb61da2339" }, - ) - await send_request(request) - -@pytest.mark.asyncio -async def test_raise_error_with_secrets(send_request): - request = rest.build_get_error_with_secrets_request() - with pytest.raises(HttpResponseError) as ex: - await send_request(request) - # The actual test shouldn't have the secrets in the str output - # Until we figure out what to do for Python, just asserting - # what the string currently is for now. - assert "The user 'user@contoso.com' is unauthorized" in str(ex.value) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_extensible_enums.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_extensible_enums.py deleted file mode 100644 index 5aa75d44a7c..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_extensible_enums.py +++ /dev/null @@ -1,77 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from async_generator import yield_, async_generator - -from extensibleenumsswaggerlowlevel.aio import PetStoreInc -from extensibleenumsswaggerlowlevel.rest import pet - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with PetStoreInc() as client: - await yield_(client) - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_get_by_pet_id(send_request_json_response): - # Now enum return are always string (Autorest.Python 3.0) - - request = pet.build_get_by_pet_id_request(pet_id="tommy") - tommy = await send_request_json_response(request) - assert tommy["DaysOfWeek"] == "Monday" - assert tommy["IntEnum"] == "1" - - request = pet.build_get_by_pet_id_request(pet_id="casper") - casper = await send_request_json_response(request) - assert casper["DaysOfWeek"] == "Weekend" - assert casper["IntEnum"] == "2" - - request = pet.build_get_by_pet_id_request(pet_id="scooby") - scooby = await send_request_json_response(request) - 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" - -@pytest.mark.asyncio -async def test_add_pet(send_request_json_response): - retriever = { - "name": "Retriever", - "IntEnum": "3", - "DaysOfWeek": "Friday" - } - request = pet.build_add_pet_request(json=retriever) - returned_pet = await send_request_json_response(request) - assert returned_pet["DaysOfWeek"] == "Friday" - assert returned_pet["IntEnum"] == "3" - assert returned_pet["name"] == "Retriever" diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_file.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_file.py deleted file mode 100644 index d27ac682a1e..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_file.py +++ /dev/null @@ -1,99 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from async_generator import yield_, async_generator -from os.path import dirname, pardir, join, realpath -import io -from bodyfilelowlevel.aio import AutoRestSwaggerBATFileService -from bodyfilelowlevel.rest.files import * - -import pytest - -cwd = dirname(realpath(__file__)) - - -@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: - await yield_(client) - - -@pytest.mark.asyncio -@pytest.mark.parametrize('client', [1000], indirect=True) -async def test_get_file(client): - file_length = 0 - with io.BytesIO() as file_handle: - request = build_get_file_request() - async with client.send_request(request, stream=True) as response: - assert not response._internal_response._released - assert not response.is_closed - assert not response.is_stream_consumed - async for data in response.iter_raw(): - # assert 0 < len(data) <= stream.block_size - file_length += len(data) - file_handle.write(data) - - assert file_length != 0 - assert response.is_closed - assert response.is_stream_consumed - assert response._internal_response._released - 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: - sample_data = hash(data.read()) - assert sample_data == hash(file_handle.getvalue()) - -@pytest.mark.asyncio -@pytest.mark.parametrize('client', [4096], indirect=True) -async def test_get_empty_file(client): - file_length = 0 - with io.BytesIO() as file_handle: - request = build_get_empty_file_request() - async with client.send_request(request, stream=True) as response: - assert not response._internal_response._released - - async for data in response.iter_raw(): - file_length += len(data) - file_handle.write(data) - - assert file_length == 0 - -@pytest.mark.asyncio -@pytest.mark.parametrize('client', [4096], indirect=True) -async def test_files_long_running(client): - file_length = 0 - request = build_get_file_large_request() - async with client.send_request(request, stream=True) as response: - async for data in response.iter_bytes(): - assert 0 < len(data) <= response.block_size - file_length += len(data) - - assert file_length == 3000 * 1024 * 1024 diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_form_data.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_form_data.py deleted file mode 100644 index 88020b29898..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_form_data.py +++ /dev/null @@ -1,159 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from async_generator import yield_, async_generator -import subprocess -import sys -import io -import os -import tempfile -from os.path import dirname, pardir, join, realpath - -cwd = dirname(realpath(__file__)) -log_level = int(os.environ.get('PythonLogLevel', 30)) - -tests = realpath(join(cwd, pardir, "Expected", "AcceptanceTests")) -sys.path.append(join(tests, "BodyFormData")) - - -from bodyformdatalowlevel.aio import AutoRestSwaggerBATFormDataService -from bodyformdatalowlevel.rest import formdata -import pytest - -@pytest.fixture -def dummy_file(): - 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(connection_data_block_size=None): - 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 - ) as client: - await yield_(client) - -@pytest.mark.skip("Not generating formdata bodies anymore.") -@pytest.mark.asyncio -async def test_file_upload_stream(client): - - test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') - result = io.BytesIO() - with io.BytesIO(test_bytes) as stream_data: - files = { - "fileContent": stream_data, - "fileName": "UploadFile.txt", - } - request = formdata.build_upload_file_request(files=files) - async with client.send_request(request, stream=True) as response: - response.raise_for_status() - async for data in response.iter_bytes(): - result.write(data) - assert result.getvalue().decode() == test_string - -@pytest.mark.skip("Not generating formdata bodies anymore.") -@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 = { - "fileContent": upload_data, - "fileName": name, - } - request = formdata.build_upload_file_request(files=files) - async with client.send_request(request, stream=True) as response: - response.raise_for_status() - async for data in response.iter_bytes(): - result.write(data) - 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') - - result = io.BytesIO() - with io.BytesIO(test_bytes) as stream_data: - request = formdata.build_upload_file_via_body_request(content=stream_data) - async with client.send_request(request, stream=True) as response: - response.raise_for_status() - async for data in response.iter_bytes(): - result.write(data) - assert result.getvalue().decode() == test_string - - result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: - request = formdata.build_upload_file_via_body_request(content=upload_data) - async with client.send_request(request, stream=True) as response: - response.raise_for_status() - async for data in response.iter_bytes(): - result.write(data) - 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') - - @async_generator - async 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))) - if not block: - break - await yield_(block) - - result = io.BytesIO() - with io.BytesIO(test_bytes) as stream_data: - streamed_upload = stream_upload(stream_data, len(test_string), 2) - request = formdata.build_upload_file_via_body_request(content=streamed_upload, headers={"Content-Type": "application/octet-stream"}) - async with client.send_request(request, stream=True) as response: - response.raise_for_status() - async for data in response.iter_bytes(): - result.write(data) - assert result.getvalue().decode() == test_string - - result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: - streamed_upload = stream_upload(upload_data, len("Test file"), 2) - request = formdata.build_upload_file_via_body_request(content=streamed_upload) - async with client.send_request(request, stream=True) as response: - response.raise_for_status() - async for data in response.iter_bytes(): - result.write(data) - assert result.getvalue().decode() == "Test file" \ No newline at end of file diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_header.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_header.py deleted file mode 100644 index 8f86e25e67e..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_header.py +++ /dev/null @@ -1,247 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import isodate -from datetime import datetime, timedelta -from async_generator import yield_, async_generator -from base64 import b64decode - -from headerlowlevel.aio import AutoRestSwaggerBATHeaderService -from headerlowlevel.rest import header - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestSwaggerBATHeaderService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_value_response_header(client, base_send_request): - async def _send_request(request): - return (await base_send_request(client, request)).headers['value'] - return _send_request - -# NOTE: in llc, we don't know to deserialize response headers as int / datetime etc. So you'll see they'll just be strings, not ints etc -@pytest.mark.asyncio -async def test_integer(send_request, send_request_value_response_header): - - request = header.build_param_integer_request(scenario="positive", value=1) - await send_request(request) - request = header.build_param_integer_request(scenario="negative", value=-2) - await send_request(request) - - request = header.build_response_integer_request(scenario="positive") - assert await send_request_value_response_header(request) == "1" - - request = header.build_response_integer_request(scenario="negative") - assert await send_request_value_response_header(request) == "-2" - -@pytest.mark.asyncio -async def test_long(send_request, send_request_value_response_header): - request = header.build_param_long_request(scenario="positive", value=105) - await send_request(request) - request = header.build_param_long_request(scenario="negative", value=-2) - await send_request(request) - - request = header.build_response_long_request(scenario="positive") - assert await send_request_value_response_header(request) == "105" - - request = header.build_response_long_request(scenario="negative") - assert await send_request_value_response_header(request) == "-2" - -@pytest.mark.asyncio -async def test_float(send_request, send_request_value_response_header): - request = header.build_param_float_request(scenario="positive", value=0.07) - await send_request(request) - - request = header.build_param_float_request(scenario="negative", value=-3.0) - await send_request(request) - - request = header.build_response_float_request(scenario="positive") - assert abs(0.07 - float(await send_request_value_response_header(request))) < 0.00001 - - request = header.build_response_float_request(scenario="negative") - assert abs(-3.0 - float(await send_request_value_response_header(request))) < 0.00001 - -@pytest.mark.asyncio -async def test_double(send_request, send_request_value_response_header): - request = header.build_param_double_request(scenario="positive", value=7e120) - await send_request(request) - - request = header.build_param_double_request(scenario="negative", value=-3.0) - await send_request(request) - - request = header.build_response_double_request(scenario="positive") - assert await send_request_value_response_header(request) == "7e+120" - - request = header.build_response_double_request(scenario="negative") - assert await send_request_value_response_header(request) == "-3" - -@pytest.mark.asyncio -async def test_bool(send_request, send_request_value_response_header): - request = header.build_param_bool_request(scenario="true", value=True) - await send_request(request) - request = header.build_param_bool_request(scenario="false", value=False) - await send_request(request) - - request = header.build_response_bool_request(scenario="true") - assert await send_request_value_response_header(request) == 'true' - - request = header.build_response_bool_request(scenario="false") - assert await send_request_value_response_header(request) == 'false' - -@pytest.mark.asyncio -async def test_string(send_request, send_request_value_response_header): - request = header.build_param_string_request(scenario="valid", value="The quick brown fox jumps over the lazy dog") - await send_request(request) - - request = header.build_param_string_request(scenario="null", value=None) - await send_request(request) - - request = header.build_param_string_request(scenario="empty", value="") - await send_request(request) - - request = header.build_response_string_request(scenario="valid") - assert await send_request_value_response_header(request) == "The quick brown fox jumps over the lazy dog" - - request = header.build_response_string_request(scenario="null") - assert await send_request_value_response_header(request) == "null" # TODO This should be None - - request = header.build_response_string_request(scenario="empty") - assert await send_request_value_response_header(request) == "" - -@pytest.mark.asyncio -async def test_enum(send_request, send_request_value_response_header): - request = header.build_param_enum_request(scenario="valid", value="GREY") - await send_request(request) - - request = header.build_param_enum_request(scenario="valid", value="GREY") - await send_request(request) - - request = header.build_param_enum_request(scenario="null", value=None) - await send_request(request) - - - request = header.build_response_enum_request(scenario="valid") - assert await send_request_value_response_header(request) == "GREY" - - # We receive an empty string. - # Starting msrest 0.4.22, we consider that if a string is not in the enum, this not - # a Deserialization issue and we return the string. - # Here we now return empty string without failin **on purpose** - # with pytest.raises(DeserializationError): - request = header.build_response_enum_request(scenario="null") - assert await send_request_value_response_header(request) == "" - -@pytest.mark.asyncio -async def test_date(send_request, send_request_value_response_header): - request = header.build_param_date_request(scenario="valid", value=isodate.parse_date("2010-01-01")) - await send_request(request) - request = header.build_param_date_request(scenario="min", value=datetime.min) - await send_request(request) - - request = header.build_response_date_request(scenario="valid") - assert await send_request_value_response_header(request) == str(isodate.parse_date("2010-01-01")) - - request = header.build_response_date_request(scenario="min") - assert await send_request_value_response_header(request) == str(isodate.parse_date("0001-01-01")) - -@pytest.mark.asyncio -async def test_datetime(send_request, send_request_value_response_header): - request = header.build_param_datetime_request(scenario="valid", value=isodate.parse_datetime("2010-01-01T12:34:56Z")) - await send_request(request) - request = header.build_param_datetime_request(scenario="min", value=datetime.min) - await send_request(request) - - request = header.build_response_datetime_request(scenario="valid") - assert await send_request_value_response_header(request) == '2010-01-01T12:34:56Z' - - request = header.build_response_datetime_request(scenario="min") - assert await send_request_value_response_header(request) == '0001-01-01T00:00:00Z' - -@pytest.mark.asyncio -async def test_datetime_rfc(send_request, send_request_value_response_header): - request = header.build_param_datetime_rfc1123_request(scenario="valid", value=isodate.parse_datetime("2010-01-01T12:34:56Z")) - await send_request(request) - - request = header.build_param_datetime_rfc1123_request(scenario="min", value=datetime.min) - await send_request(request) - - request = header.build_response_datetime_rfc1123_request(scenario="valid") - assert await send_request_value_response_header(request) == "Fri, 01 Jan 2010 12:34:56 GMT" - - # 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 - request = header.build_response_datetime_rfc1123_request(scenario="min") - assert await send_request_value_response_header(request) == "Mon, 01 Jan 0001 00:00:00 GMT" - -@pytest.mark.asyncio -async def test_duration(send_request, send_request_value_response_header): - request = header.build_param_duration_request(scenario="valid", value=timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11)) - await send_request(request) - - request = header.build_response_duration_request(scenario="valid") - assert await send_request_value_response_header(request) == 'P123DT22H14M12.011S' # raw str of the above timedelta - -@pytest.mark.asyncio -async def test_byte(send_request, send_request_value_response_header): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') - request = header.build_param_byte_request(scenario="valid", value=u_bytes) - await send_request(request) - - request = header.build_response_byte_request(scenario="valid") - assert bytearray(b64decode(await send_request_value_response_header(request))) == u_bytes - -@pytest.mark.asyncio -async def test_response_existing_key(send_request): - - request = header.build_param_existing_key_request(user_agent_parameter="overwrite") - await send_request(request) - request = header.build_response_existing_key_request() - assert (await send_request(request)).headers['User-Agent'] == "overwrite" - -@pytest.mark.asyncio -async def test_response_protected_key(send_request): - # This test is only valid for C#, which content-type can't be override this way - #client.header.param_protected_key("text/html") - - # This test has different result compare to C#, which content-type is saved in another place. - request = header.build_response_protected_key_request() - assert (await send_request(request)).headers['Content-Type'] == "text/html; charset=utf-8" - -@pytest.mark.asyncio -async def test_custom_request_id(send_request): - custom_headers = {"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} - request = header.build_custom_request_id_request(headers=custom_headers) - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_hooks.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_hooks.py deleted file mode 100644 index 545b22cb1c9..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_hooks.py +++ /dev/null @@ -1,56 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from azure.core.pipeline.policies import CustomHookPolicy -from bodyarraylowlevel.aio import AutoRestSwaggerBATArrayService -from bodyarraylowlevel.rest import array - -def is_rest(obj): - return hasattr(obj, "content") - -@pytest.mark.asyncio -async def test_raw_request_hook_send_request(): - def _callback(request): - assert 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.send_request(array.build_get_array_empty_request()) - assert "I entered the callback!" in str(ex.value) - -@pytest.mark.asyncio -async def test_raw_response_hook_send_request(): - def _callback(response): - assert 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: - await client.send_request(array.build_get_array_empty_request()) - assert "I entered the callback!" in str(ex.value) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_http.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_http.py deleted file mode 100644 index 9d5e9a8412e..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_http.py +++ /dev/null @@ -1,540 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import requests -from async_generator import yield_, async_generator - -from azure.core.exceptions import HttpResponseError -from azure.core.pipeline.policies import ContentDecodePolicy, AsyncRetryPolicy, HeadersPolicy, AsyncRedirectPolicy - -from httpinfrastructurelowlevel.aio import AutoRestHttpInfrastructureTestService -from httpinfrastructurelowlevel.rest import ( - multiple_responses, - http_server_failure, - http_failure, - http_redirects, - http_retry, - http_success, - http_client_failure, -) - -import pytest - - -@pytest.fixture -@async_generator -async def client(cookie_policy): - """Create a AutoRestHttpInfrastructureTestService client with test server credentials.""" - policies = [ - HeadersPolicy(), - ContentDecodePolicy(), - AsyncRedirectPolicy(), - AsyncRetryPolicy(), - cookie_policy - ] - async with AutoRestHttpInfrastructureTestService(policies=policies) as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.fixture -def send_request_assert_status(client, base_send_request): - async def _send_request(request, status_code): - response = await base_send_request(client, request) - assert response.status_code == status_code - return _send_request - -@pytest.fixture -def send_request_assert_raises_with_message(client, base_send_request): - async def _send_request(request, message): - with pytest.raises(HttpResponseError) as ex: - await base_send_request(client, request) - assert ex.value.message == message - return _send_request - -@pytest.fixture -def send_request_assert_raises_with_status(client, base_send_request): - async def _send_request(request, status_code): - with pytest.raises(HttpResponseError) as ex: - await base_send_request(client, request) - assert ex.value.status_code == status_code - return _send_request - -@pytest.fixture -def send_request_assert_raises_with_status_and_message(client, base_send_request): - async def _send_request(request, status_code, message): - with pytest.raises(HttpResponseError) as ex: - await base_send_request(client, request) - assert ex.value.status_code == status_code - assert ex.value.message == message - assert message in str(ex.value) - return _send_request - -@pytest.fixture -def send_request_assert_raises_with_status_and_response_contains_message(client, base_send_request): - async def _send_request(request, status_code, message): - with pytest.raises(HttpResponseError) as ex: - await base_send_request(client, request) - assert ex.value.status_code == status_code - assert ex.value.response.json()['message'] == message - return _send_request - -@pytest.mark.asyncio -async def test_get200_model204(send_request, send_request_assert_status, send_request_assert_raises_with_status_and_response_contains_message): - # a lot of these tests raised in high level bc we made some 200 status codes errors in high level - # can't do this in low level, so these don't actually raise - request = multiple_responses.build_get200_model204_no_model_default_error200_valid_request() - await send_request_assert_status(request, 200) - - request = multiple_responses.build_get200_model204_no_model_default_error201_invalid_request() - await send_request_assert_status(request, 201) - - request = multiple_responses.build_get200_model204_no_model_default_error202_none_request() - await send_request_assert_status(request, 202) - - request = multiple_responses.build_get200_model204_no_model_default_error204_valid_request() - - assert (await send_request(request)).text() == '' - - request = multiple_responses.build_get200_model204_no_model_default_error400_valid_request() - await send_request_assert_raises_with_status_and_response_contains_message(request, 400, "client error") - -@pytest.mark.asyncio -async def test_get200_model201(send_request_json_response, send_request_assert_status, send_request_assert_raises_with_status_and_response_contains_message): - request = multiple_responses.build_get200_model201_model_default_error200_valid_request() - await send_request_assert_status(request, 200) - - request = multiple_responses.build_get200_model201_model_default_error201_valid_request() - b_model = await send_request_json_response(request) - assert b_model is not None - assert b_model['statusCode'] == "201" - assert b_model['textStatusCode'] == "Created" - - request = multiple_responses.build_get200_model201_model_default_error400_valid_request() - await send_request_assert_raises_with_status_and_response_contains_message(request, 400, "client error") - -@pytest.mark.asyncio -async def test_get200_model_a201_model_c404(send_request_json_response, send_request_assert_raises_with_status_and_response_contains_message, send_request_assert_raises_with_status): - request = multiple_responses.build_get200_model_a201_model_c404_model_d_default_error200_valid_request() - a_model = await send_request_json_response(request) - assert a_model['statusCode']== "200" - - request = multiple_responses.build_get200_model_a201_model_c404_model_d_default_error201_valid_request() - - c_model = await send_request_json_response(request) - assert c_model['httpCode'] == "201" - - request = multiple_responses.build_get200_model_a201_model_c404_model_d_default_error404_valid_request() - await send_request_assert_raises_with_status(request, 404) # in high level, this doesn't raise and returns a model since we've made 404 a valid status code. can't do that in llc - - request = multiple_responses.build_get200_model_a201_model_c404_model_d_default_error400_valid_request() - await send_request_assert_raises_with_status_and_response_contains_message(request, 400, "client error") - -@pytest.mark.asyncio -async def test_get202_none204(send_request, send_request_assert_raises_with_status, send_request_assert_raises_with_status_and_response_contains_message): - request = multiple_responses.build_get202_none204_none_default_error202_none_request() - await send_request(request) - - request = multiple_responses.build_get202_none204_none_default_error204_none_request() - await send_request(request) - - request = multiple_responses.build_get202_none204_none_default_error400_valid_request() - await send_request_assert_raises_with_status_and_response_contains_message(request, 400, "client error") - - request = multiple_responses.build_get202_none204_none_default_none202_invalid_request() - await send_request(request) - - request = multiple_responses.build_get202_none204_none_default_none204_none_request() - await send_request(request) - - request = multiple_responses.build_get202_none204_none_default_none400_none_request() - await send_request_assert_raises_with_status(request, 400) - - request = multiple_responses.build_get202_none204_none_default_none400_invalid_request() - await send_request_assert_raises_with_status(request, 400) - -@pytest.mark.asyncio -async def test_get_default_model_a200(send_request, send_request_assert_status): - request = multiple_responses.build_get_default_model_a200_valid_request() - await send_request_assert_status(request, 200) - - request = multiple_responses.build_get_default_model_a200_none_request() - assert (await send_request(request)).text() == '' - - request = multiple_responses.build_get_default_model_a200_valid_request() - await send_request(request) - request = multiple_responses.build_get_default_model_a200_none_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_get_default_none200(send_request): - request = multiple_responses.build_get_default_none200_invalid_request() - await send_request(request) - - requst = multiple_responses.build_get_default_none200_none_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_get_default_none400(send_request_assert_raises_with_status): - request = multiple_responses.build_get_default_none400_invalid_request() - await send_request_assert_raises_with_status(request, 400) - - request = multiple_responses.build_get_default_none400_none_request() - await send_request_assert_raises_with_status(request, 400) - -@pytest.mark.asyncio -async def test_get200_model_a200(send_request, send_request_assert_status): - request = multiple_responses.build_get200_model_a200_none_request() - assert (await send_request(request)).text() == '' - - request = multiple_responses.build_get200_model_a200_valid_request() - await send_request_assert_status(request, 200) - - request = multiple_responses.build_get200_model_a200_invalid_request() - await send_request_assert_status(request, 200) # in high level it's supposed to deserialize as exception model "MyException", can't do that in LLC - -@pytest.mark.asyncio -async def test_get200_model_a400(send_request_assert_raises_with_status): - request = multiple_responses.build_get200_model_a400_none_request() - await send_request_assert_raises_with_status(request, 400) - - request = multiple_responses.build_get200_model_a400_valid_request() - await send_request_assert_raises_with_status(request, 400) - - request = multiple_responses.build_get200_model_a400_invalid_request() - await send_request_assert_raises_with_status(request, 400) - -@pytest.mark.asyncio -async def test_get200_model_a202(send_request_assert_status): - request = multiple_responses.build_get200_model_a202_valid_request() - await send_request_assert_status(request, 202) # raises in HLC bc we've marked all status codes that are not "200" as errors - -@pytest.mark.asyncio -async def test_server_error_status_codes_501(send_request_assert_raises_with_status): - request = http_server_failure.build_head501_request() - await send_request_assert_raises_with_status(request, requests.codes.not_implemented) - - request = http_server_failure.build_get501_request() - await send_request_assert_raises_with_status(request, requests.codes.not_implemented) - -@pytest.mark.asyncio -async def test_server_error_status_codes_505(send_request_assert_raises_with_status): - request = http_server_failure.build_post505_request() - await send_request_assert_raises_with_status(request, requests.codes.http_version_not_supported) - - request = http_server_failure.build_delete505_request() - await send_request_assert_raises_with_status(request, requests.codes.http_version_not_supported) - -@pytest.mark.asyncio -async def test_retry_status_codes_408(send_request): - request = http_retry.build_head408_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_retry_status_codes_502(send_request): - request = http_retry.build_get502_request() - await send_request(request) - - request = http_retry.build_options502_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_retry_status_codes_500(send_request): - request = http_retry.build_put500_request() - await send_request(request) - request = http_retry.build_patch500_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_retry_status_codes_503(send_request): - request = http_retry.build_post503_request() - await send_request(request) - - request = http_retry.build_delete503_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_retry_status_codes_504(send_request): - request = http_retry.build_put504_request() - await send_request(request) - - request = http_retry.build_patch504_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_error_status_codes_400(send_request_assert_raises_with_status): - request = http_client_failure.build_head400_request() - await send_request_assert_raises_with_status(request, requests.codes.bad_request) - - request = http_client_failure.build_get400_request() - await send_request_assert_raises_with_status(request, requests.codes.bad_request) - - # TODO, 4042586: Support options operations in swagger modeler - #self.assert_raises_with_status(requests.codes.bad_request, - # client.http_client_failure.options400) - - request = http_client_failure.build_put400_request() - await send_request_assert_raises_with_status(request, requests.codes.bad_request) - - request = http_client_failure.build_patch400_request() - await send_request_assert_raises_with_status(request, requests.codes.bad_request) - - request = http_client_failure.build_post400_request() - await send_request_assert_raises_with_status(request, requests.codes.bad_request) - - request = http_client_failure.build_delete400_request() - await send_request_assert_raises_with_status(request, requests.codes.bad_request) - -@pytest.mark.asyncio -async def test_error_status_codes_401(send_request_assert_raises_with_status): - request = http_client_failure.build_head401_request() - await send_request_assert_raises_with_status(request, requests.codes.unauthorized) - -@pytest.mark.asyncio -async def test_error_status_codes_402(send_request_assert_raises_with_status): - request = http_client_failure.build_get402_request() - await send_request_assert_raises_with_status(request, requests.codes.payment_required) - -@pytest.mark.asyncio -async def test_error_status_codes_403(send_request_assert_raises_with_status): - # TODO, 4042586: Support options operations in swagger modeler - #self.assert_raises_with_status(requests.codes.forbidden, - # client.http_client_failure.options403) - - request = http_client_failure.build_get403_request() - await send_request_assert_raises_with_status(request, requests.codes.forbidden) - -@pytest.mark.asyncio -async def test_error_status_codes_404(send_request_assert_raises_with_status): - request = http_client_failure.build_put404_request() - await send_request_assert_raises_with_status(request, requests.codes.not_found) - -@pytest.mark.asyncio -async def test_error_status_codes_405(send_request_assert_raises_with_status): - request = http_client_failure.build_patch405_request() - await send_request_assert_raises_with_status(request, requests.codes.method_not_allowed) - -@pytest.mark.asyncio -async def test_error_status_codes_406(send_request_assert_raises_with_status): - request = http_client_failure.build_post406_request() - await send_request_assert_raises_with_status(request, requests.codes.not_acceptable) - -@pytest.mark.asyncio -async def test_error_status_codes_407(send_request_assert_raises_with_status): - request = http_client_failure.build_delete407_request() - await send_request_assert_raises_with_status(request, requests.codes.proxy_authentication_required) - -@pytest.mark.asyncio -async def test_error_status_codes_409(send_request_assert_raises_with_status): - request = http_client_failure.build_put409_request() - await send_request_assert_raises_with_status(request, requests.codes.conflict) - -@pytest.mark.asyncio -async def test_error_status_codes_410(send_request_assert_raises_with_status): - request = http_client_failure.build_head410_request() - await send_request_assert_raises_with_status(request, requests.codes.gone) - -@pytest.mark.asyncio -async def test_error_status_codes_411(send_request_assert_raises_with_status): - - request = http_client_failure.build_get411_request() - await send_request_assert_raises_with_status(request, requests.codes.length_required) - - # TODO, 4042586: Support options operations in swagger modeler - #self.assert_raises_with_status(requests.codes.precondition_failed, - # client.http_client_failure.options412) - - request = http_client_failure.build_get412_request() - await send_request_assert_raises_with_status(request, requests.codes.precondition_failed) - - request = http_client_failure.build_put413_request() - await send_request_assert_raises_with_status(request, requests.codes.request_entity_too_large) - - request = http_client_failure.build_patch414_request() - await send_request_assert_raises_with_status(request, requests.codes.request_uri_too_large) - - request = http_client_failure.build_post415_request() - await send_request_assert_raises_with_status(request, requests.codes.unsupported_media) - - request = http_client_failure.build_get416_request() - await send_request_assert_raises_with_status(request, requests.codes.requested_range_not_satisfiable) - - request = http_client_failure.build_delete417_request() - await send_request_assert_raises_with_status(request, requests.codes.expectation_failed) - - request = http_client_failure.build_head429_request() - await send_request_assert_raises_with_status(request, 429) - -@pytest.mark.asyncio -async def test_redirect_to_300(send_request_assert_status): - request = http_redirects.build_get300_request() - await send_request_assert_status(request, 200) - - request = http_redirects.build_head300_request() - await send_request_assert_status(request, 200) - -@pytest.mark.asyncio -async def test_redirect_to_301(send_request_assert_status): - request = http_redirects.build_head301_request() - await send_request_assert_status(request, 200) - - - request = http_redirects.build_get301_request() - await send_request_assert_status(request, 200) - - request = http_redirects.build_put301_request() - await send_request_assert_status(request, requests.codes.moved_permanently) - -@pytest.mark.asyncio -async def test_redirect_to_302(send_request_assert_status): - request = http_redirects.build_head302_request() - await send_request_assert_status(request, 200) - - request = http_redirects.build_get302_request() - await send_request_assert_status(request, 200) - - request = http_redirects.build_patch302_request() - await send_request_assert_status(request, requests.codes.found) - -@pytest.mark.asyncio -async def test_redicret_to_303(send_request_assert_status): - request = http_redirects.build_post303_request() - await send_request_assert_status(request, 200) - -@pytest.mark.asyncio -async def test_redirect_to_307(send_request_assert_status): - request = http_redirects.build_head307_request() - await send_request_assert_status(request, 200) - - request = http_redirects.build_get307_request() - await send_request_assert_status(request, 200) - - request = http_redirects.build_options307_request() - await send_request_assert_status(request, 200) - - request = http_redirects.build_put307_request() - await send_request_assert_status(request, 200) - - request = http_redirects.build_post307_request() - await send_request_assert_status(request, 200) - - request = http_redirects.build_patch307_request() - await send_request_assert_status(request, 200) - - request = http_redirects.build_delete307_request() - await send_request_assert_status(request, 200) - -@pytest.mark.asyncio -async def test_bad_request_status_assert(send_request_assert_raises_with_message): - request = http_failure.build_get_empty_error_request() - await send_request_assert_raises_with_message(request, "Operation returned an invalid status 'Bad Request'") - -@pytest.mark.asyncio -async def test_no_error_model_status_assert(send_request_assert_raises_with_status_and_response_contains_message): - request = http_failure.build_get_no_model_error_request() - await send_request_assert_raises_with_status_and_response_contains_message(request, requests.codes.bad_request, "NoErrorModel") - -@pytest.mark.asyncio -async def test_success_status_codes_200(send_request): - request = http_success.build_head200_request() - await send_request(request) - request = http_success.build_get200_request() - assert (await send_request(request)).text - - request = http_success.build_put200_request() - await send_request(request) - - request = http_success.build_post200_request() - await send_request(request) - - request = http_success.build_patch200_request() - await send_request(request) - - request = http_success.build_delete200_request() - await send_request(request) - - # TODO, 4042586: Support options operations in swagger modeler - #assert client.http_success.options200() - -@pytest.mark.asyncio -async def test_success_status_codes_201(send_request): - request = http_success.build_put201_request() - await send_request(request) - - request = http_success.build_post201_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_success_status_codes_202(send_request): - request = http_success.build_put202_request() - await send_request(request) - - request = http_success.build_post202_request() - await send_request(request) - - request = http_success.build_patch202_request() - await send_request(request) - - request = http_success.build_delete202_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_success_status_codes_204(send_request): - request = http_success.build_head204_request() - await send_request(request) - - request = http_success.build_put204_request() - await send_request(request) - - request = http_success.build_post204_request() - await send_request(request) - - request = http_success.build_delete204_request() - await send_request(request) - - request = http_success.build_patch204_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_success_status_codes_404(send_request_assert_raises_with_status): - # raises bc in high level we're able to mark 404 as a valid status code, but can't do that in llc - request = http_success.build_head404_request() - await send_request_assert_raises_with_status(request, 404) - -@pytest.mark.asyncio -async def test_empty_no_content(send_request_assert_raises_with_status): - request = http_failure.build_get_no_model_empty_request() - await send_request_assert_raises_with_status(request, requests.codes.bad_request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_integer.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_integer.py deleted file mode 100644 index 94c5f956234..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_integer.py +++ /dev/null @@ -1,127 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from async_generator import yield_, async_generator -import datetime -from azure.core.exceptions import DecodeError - -from bodyintegerlowlevel.aio import AutoRestIntegerTestService -from bodyintegerlowlevel.rest import int as int_rest -import calendar - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - 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 - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestIntegerTestService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_max_min_32_bit(send_request): - request = int_rest.build_put_max32_request(json=2147483647) # sys.maxint - await send_request(request) - - request = int_rest.build_put_min32_request(json=-2147483648) - await send_request(request) - -@pytest.mark.asyncio -async def test_max_min_64_bit(send_request): - request = int_rest.build_put_max64_request(json=9223372036854776000) # sys.maxsize - await send_request(request) - - request = int_rest.build_put_min64_request(json=-9223372036854776000) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_null_and_invalid(send_request): - request = int_rest.build_get_null_request() - await send_request(request) - - request = int_rest.build_get_invalid_request() - with pytest.raises(DecodeError): - await send_request(request) - -@pytest.mark.asyncio -async def test_get_overflow(send_request): - # Testserver excepts these to fail, but they won't in Python and it's ok. - - request = int_rest.build_get_overflow_int32_request() - await send_request(request) - - request = int_rest.build_get_overflow_int64_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_get_underflow(send_request): - request = int_rest.build_get_underflow_int32_request() - await send_request(request) - - request = int_rest.build_get_underflow_int64_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_unix_time_date(send_request): - unix_date = datetime.datetime(year=2016, month=4, day=13) - request = int_rest.build_put_unix_time_date_request(json=int(calendar.timegm(unix_date.utctimetuple()))) - await send_request(request) - - request = int_rest.build_get_unix_time_request() - assert unix_date.utctimetuple() == datetime.datetime.fromtimestamp((await send_request(request)).json(), TZ_UTC).utctimetuple() - -@pytest.mark.asyncio -async def test_get_null_and_invalid_unix_time(send_request): - request = int_rest.build_get_null_unix_time_request() - assert (await send_request(request)).text() == '' - - request = int_rest.build_get_invalid_unix_time_request() - with pytest.raises(DecodeError): - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_media_types.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_media_types.py deleted file mode 100644 index cdf34e4ba4e..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_media_types.py +++ /dev/null @@ -1,111 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from mediatypeslowlevel.aio import MediaTypesClient -from mediatypeslowlevel.rest import * -from async_generator import yield_, async_generator -import json - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with MediaTypesClient() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_pdf(send_request_json_response): - request = build_analyze_body_request(content=b"PDF", content_type="application/pdf") - assert await send_request_json_response(request) == "Nice job with PDF" - -@pytest.mark.asyncio -async def test_json(send_request_json_response): - request = build_analyze_body_request(json={"source":"foo"}) - assert await send_request_json_response(request) == "Nice job with JSON" - -@pytest.mark.asyncio -async def test_content_type_with_encoding(send_request_json_response): - request = build_content_type_with_encoding_request(content="hello", content_type='text/plain; charset=UTF-8') - assert await send_request_json_response(request) == "Nice job sending content type with encoding" - -@pytest.mark.asyncio -async def test_pdf_no_accept_header(send_request): - request = build_analyze_body_no_accept_header_request(content=b"PDF", content_type="application/pdf") - await send_request(request) - -@pytest.mark.asyncio -async def test_json_no_accept_header(send_request): - request = build_analyze_body_no_accept_header_request(json={"source":"foo"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_binary_body_two_content_types(send_request): - json_input = json.dumps({"hello":"world"}) - request = build_binary_body_with_two_content_types_request(content=json_input, content_type="application/json") - await send_request(request) - - content = b"hello, world" - request = build_binary_body_with_two_content_types_request(content=content, content_type="application/octet-stream") - await send_request(request) - -@pytest.mark.asyncio -async def test_binary_body_three_content_types(send_request): - json_input = json.dumps({"hello":"world"}) - request = build_binary_body_with_three_content_types_request(content=json_input, content_type="application/json") - await send_request(request) - - content = b"hello, world" - request = build_binary_body_with_three_content_types_request(content=content, content_type="application/octet-stream") - await send_request(request) - - content = "hello, world" - request = build_binary_body_with_three_content_types_request(content=content, content_type="text/plain") - await send_request(request) - -@pytest.mark.asyncio -async def test_body_three_types(send_request): - request = build_body_three_types_request(json={"hello":"world"}) - await send_request(request) - - content = b"hello, world" - request = build_body_three_types_request(content=content, content_type="application/octet-stream") - await send_request(request) - - content = "hello, world" - request = build_body_three_types_request(content=content, content_type="text/plain") - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_merge_patch_json.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_merge_patch_json.py deleted file mode 100644 index 672a6de16bb..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_merge_patch_json.py +++ /dev/null @@ -1,46 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from mergepatchjsonlowlevel import rest -from mergepatchjsonlowlevel.aio import MergePatchJsonClient - -import pytest - -@pytest.fixture -async def client(): - async with MergePatchJsonClient() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_merge_patch_json(send_request): - request = rest.build_patch_single_request(json={"foo": "bar"}, content_type="application/merge-patch+json") - assert request.headers["Content-Length"] == "14" - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_model_flattening.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_model_flattening.py deleted file mode 100644 index caf60c043ae..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_model_flattening.py +++ /dev/null @@ -1,300 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from async_generator import yield_, async_generator -from modelflatteninglowlevel.aio import AutoRestResourceFlatteningTestService -from modelflatteninglowlevel import rest - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestResourceFlatteningTestService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - - -@pytest.mark.asyncio -async def test_flattening_array(send_request, send_request_json_response): - #Array - request = rest.build_get_array_request() - result = await send_request_json_response(request) - 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"] - # Resource 2 - 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'] - - json = [ - { - 'tags': { - 'tag1': 'value1', - 'tag2': 'value3' - }, - 'location': 'West US' - }, - { - 'location': 'Building 44' - } - ] - request = rest.build_put_array_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_flattening_dictionary(send_request, send_request_json_response): - - request = rest.build_get_dictionary_request() - result = await send_request_json_response(request) - 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"] - # Resource 2 - 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'] - - json = { - "Resource1": { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, - "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } - }, - "Resource2": { - "location": "Building 44", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } - } - - request = rest.build_put_dictionary_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_flattening_complex_object(send_request, send_request_json_response): - - #ResourceCollection - request = rest.build_get_resource_collection_request() - result = await send_request_json_response(request) - - #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"] - # Resource 2 - 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'] - - #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"] - # Resource 2 - 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'] - - #productresource - assert "7" == result['productresource']['id'] - assert "Resource7" == result['productresource']['name'] - - json = { - "productresource": { - "location": "India", - "properties": { - "p.name": "Azure", - "type": "Flat" - } - }, - "arrayofresources": [ - { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, - "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } - }, - { - "location": "East US", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } - ], - "dictionaryofresources": { - "Resource1": { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, - "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } - }, - "Resource2": { - "location": "Building 44", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } - } - } - request = rest.build_put_resource_collection_request(json=json) - await send_request(request) - -@pytest.mark.asyncio -async def test_model_flattening_simple(send_request_json_response): - json = { - "base_product_id": "123", - "base_product_description": "product description", - "details": { - "max_product_display_name": "max name", - "max_product_capacity": "Large", - "max_product_image": { - "generic_value": "https://generic", - "@odata.value": "http://foo" - } - } - } - request = rest.build_put_simple_product_request(json=json) - result = await send_request_json_response(request) - assert json == result - -@pytest.mark.asyncio -async def test_model_flattening_with_parameter_flattening(send_request_json_response): - - json = { - "base_product_id": "123", - "base_product_description": "product description", - "details": { - "max_product_display_name": "max name", - "max_product_capacity": "Large", - "max_product_image": { - "@odata.value": "http://foo" - } - } - } - - request = rest.build_post_flattened_simple_product_request(json=json) - result = await send_request_json_response(request) - assert result == json - -@pytest.mark.asyncio -async def test_model_flattening_with_grouping(send_request_json_response): - json = { - "base_product_id": "123", - "base_product_description": "product description", - "details": { - "max_product_display_name": "max name", - "max_product_capacity": "Large", - "max_product_image": { - "@odata.value": "http://foo" - } - } - } - request = rest.build_put_simple_product_with_grouping_request( - name='groupproduct', - json=json - ) - result = await send_request_json_response(request) - assert result == json diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_multiple_inheritance.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_multiple_inheritance.py deleted file mode 100644 index e1c725cda27..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_multiple_inheritance.py +++ /dev/null @@ -1,97 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - - -from multipleinheritancelowlevel.aio import MultipleInheritanceServiceClient -from multipleinheritancelowlevel.rest import * -from async_generator import yield_, async_generator -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with MultipleInheritanceServiceClient() as client: - await yield_(client) - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_get_pet(send_request_json_response): - request = build_get_pet_request() - assert {"name": "Peanut"} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_put_pet(send_request_json_response): - request = build_put_pet_request(json={"name": "Butter"}) - result = await send_request_json_response(request) - assert result == "Pet was correct!" - -@pytest.mark.asyncio -async def test_get_horse(send_request_json_response): - request = build_get_horse_request() - assert {"name": "Fred", "isAShowHorse": True} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_put_horse(send_request_json_response): - request = build_put_horse_request(json={"name": "General", "isAShowHorse": False}) - result = await send_request_json_response(request) - assert result == "Horse was correct!" - -@pytest.mark.asyncio -async def test_get_feline(send_request_json_response): - request = build_get_feline_request() - assert {"meows": True, "hisses": True} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_put_feline(send_request_json_response): - request = build_put_feline_request(json={"meows": False, "hisses": True}) - result = await send_request_json_response(request) - assert result == "Feline was correct!" - -@pytest.mark.asyncio -async def test_get_cat(send_request_json_response): - request = build_get_cat_request() - assert {"name": "Whiskers", "likesMilk": True, "meows": True, "hisses": True} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_put_cat(send_request_json_response): - request = build_put_cat_request(json={"name": "Boots", "likesMilk": False, "meows": True, "hisses": False}) - assert await send_request_json_response(request) == "Cat was correct!" - -@pytest.mark.asyncio -async def test_get_kitten(send_request_json_response): - request = build_get_kitten_request() - assert {"name": "Gatito", "likesMilk": True, "meows": True, "hisses": True, "eatsMiceYet": False} == await send_request_json_response(request) - -@pytest.mark.asyncio -async def test_put_kitten(send_request_json_response): - request = build_put_kitten_request(json={"name": "Kitty", "likesMilk": False, "meows": True, "hisses": False, "eatsMiceYet": True}) - assert "Kitten was correct!" == await send_request_json_response(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_non_string_enums.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_non_string_enums.py deleted file mode 100644 index c393797884a..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_non_string_enums.py +++ /dev/null @@ -1,62 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from nonstringenumslowlevel.aio import NonStringEnumsClient -from nonstringenumslowlevel.rest import int, float -from async_generator import yield_, async_generator - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with NonStringEnumsClient() as client: - await yield_(client) - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_put_int_enum(send_request_json_response): - request = int.build_put_request(json=200) - assert await send_request_json_response(request) == "Nice job posting an int enum" - -@pytest.mark.asyncio -async def test_get_int_enum(send_request_json_response): - request = int.build_get_request() - assert await send_request_json_response(request) == 429 - -@pytest.mark.asyncio -async def test_put_float_enum(send_request_json_response): - request = float.build_put_request(json=200.4) - assert await send_request_json_response(request) == "Nice job posting a float enum" - -@pytest.mark.asyncio -async def test_get_float_enum(send_request_json_response): - request = float.build_get_request() - assert await send_request_json_response(request) == 429.1 diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_number.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_number.py deleted file mode 100644 index 5493c9ffabe..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_number.py +++ /dev/null @@ -1,155 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from decimal import Decimal -import pytest -from async_generator import yield_, async_generator -from azure.core.exceptions import DecodeError - -from bodynumberlowlevel.aio import AutoRestNumberTestService -from bodynumberlowlevel.rest import number - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestNumberTestService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_big_float(send_request, send_request_json_response): - request = number.build_put_big_float_request(json=3.402823e+20) - await send_request(request) - - request = number.build_get_big_float_request() - assert await send_request_json_response(request) == 3.402823e+20 - -@pytest.mark.asyncio -async def test_small_float(send_request, send_request_json_response): - request = number.build_put_small_float_request(json=3.402823e-20) - await send_request(request) - - request = number.build_get_small_float_request() - assert await send_request_json_response(request) == 3.402823e-20 - -@pytest.mark.asyncio -async def test_big_double(send_request, send_request_json_response): - request = number.build_put_big_double_request(json=2.5976931e+101) - await send_request(request) - - request = number.build_get_big_double_request() - assert await send_request_json_response(request) == 2.5976931e+101 - -@pytest.mark.asyncio -async def test_small_double(send_request, send_request_json_response): - request = number.build_put_small_double_request(json=2.5976931e-101) - await send_request(request) - - request = number.build_get_small_double_request() - assert await send_request_json_response(request) == 2.5976931e-101 - -@pytest.mark.asyncio -async def test_big_double_negative_decimal(send_request, send_request_json_response): - request = number.build_put_big_double_negative_decimal_request() - await send_request(request) - - request = number.build_get_big_double_negative_decimal_request() - assert await send_request_json_response(request) == -99999999.99 - -@pytest.mark.asyncio -async def test_big_double_positive_decimal(send_request, send_request_json_response): - request = number.build_put_big_double_positive_decimal_request() - await send_request(request) - - request = number.build_get_big_double_positive_decimal_request() - assert await send_request_json_response(request) == 99999999.99 - -@pytest.mark.asyncio -async def test_big_decimal(send_request, send_request_json_response): - request = number.build_put_big_decimal_request(json=2.5976931e+101) - await send_request(request) - - request = number.build_get_big_decimal_request() - assert await send_request_json_response(request) == 2.5976931e+101 - -@pytest.mark.asyncio -async def test_small_decimal(send_request, send_request_json_response): - request = number.build_put_small_decimal_request(json=2.5976931e-101) - await send_request(request) - - request = number.build_get_small_decimal_request() - assert await send_request_json_response(request) == 2.5976931e-101 - -@pytest.mark.asyncio -async def test_get_big_decimal_negative_decimal(send_request, send_request_json_response): - request = number.build_put_big_decimal_negative_decimal_request() - - request = number.build_get_big_decimal_negative_decimal_request() - assert await send_request_json_response(request) == -99999999.99 - -@pytest.mark.asyncio -async def test_get_big_decimal_positive_decimal(send_request, send_request_json_response): - request = number.build_put_big_decimal_positive_decimal_request() - await send_request(request) - - request = number.build_get_big_decimal_positive_decimal_request() - assert await send_request_json_response(request) == 99999999.99 - -@pytest.mark.asyncio -async def test_get_null(send_request): - request = number.build_get_null_request() - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_get_invalid_decimal(send_request): - request = number.build_get_invalid_decimal_request() - with pytest.raises(DecodeError): - await send_request(request) - -@pytest.mark.asyncio -async def test_get_invalid_double(send_request): - request = number.build_get_invalid_double_request() - with pytest.raises(DecodeError): - await send_request(request) - -@pytest.mark.asyncio -async def test_get_invalid_float(send_request): - request = number.build_get_invalid_float_request() - with pytest.raises(DecodeError): - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_object_type.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_object_type.py deleted file mode 100644 index f1c180049ad..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_object_type.py +++ /dev/null @@ -1,60 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from async_generator import yield_, async_generator -from objecttypelowlevel.aio import ObjectTypeClient -from objecttypelowlevel.rest import * -from azure.core.exceptions import HttpResponseError - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with ObjectTypeClient() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_get_object(send_request): - request = build_get_request() - assert (await send_request(request)).json() == {"message": "An object was successfully returned"} - -@pytest.mark.asyncio -async def test_put_object_success(send_request): - request = build_put_request(json={"foo": "bar"}) - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_put_object_fail(send_request): - request = build_put_request(json={"should": "fail"}) - with pytest.raises(HttpResponseError) as ex: - await send_request(request) - assert ex.value.response.json()['message'] == 'The object you passed was incorrect' diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_parameterized_endpoint.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_parameterized_endpoint.py deleted file mode 100644 index cb590df2ead..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_parameterized_endpoint.py +++ /dev/null @@ -1,44 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from parameterizedendpointlowlevel.aio import ParmaterizedEndpointClient -from parameterizedendpointlowlevel import rest - -@pytest.fixture -async def client(): - async with ParmaterizedEndpointClient(endpoint="http://localhost:3000") as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_get(send_request): - request = rest.build_get_request() - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_required_optional.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_required_optional.py deleted file mode 100644 index c29d2b3edc5..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_required_optional.py +++ /dev/null @@ -1,209 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from async_generator import yield_, async_generator -import io -from azure.core.exceptions import HttpResponseError - -from requiredoptionallowlevel.aio import AutoRestRequiredOptionalTestService -from requiredoptionallowlevel.rest import implicit, explicit - -import pytest - -@pytest.fixture -@async_generator -async def client_required(): - async with AutoRestRequiredOptionalTestService( - "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 -def send_request_required_client(client_required, base_send_request): - def _send_request(request): - return base_send_request(client_required, request) - return _send_request - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestRequiredOptionalTestService( - "required_path", - "required_query", - ) as client: - client._config.required_global_path = None - client._config.required_global_query = None - await yield_(client) - -@pytest.fixture -def send_request_client(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request -# NOTE: in the LLC version, we can't raise as many ValidationErrors as the high level convenience layer does. -# This is because we're not serializing bodies at all, so msrest doesn't have a chance to throw the validation error - - -# These clients have a required global path and query -@pytest.mark.asyncio -async def test_put_optional(send_request_required_client): - request = implicit.build_put_optional_query_request(query_parameter=None) - await send_request_required_client(request) - - request = implicit.build_put_optional_body_request(json=None) - await send_request_required_client(request) - - request = implicit.build_put_optional_header_request(query_parameter=None) - await send_request_required_client(request) - -@pytest.mark.asyncio -async def test_get_optional_global_query(send_request_required_client): - request = implicit.build_get_optional_global_query_request(optional_global_query=None) - await send_request_required_client(request) - -@pytest.mark.asyncio -async def test_post_optional_integer(send_request_required_client): - request = explicit.build_post_optional_integer_parameter_request(json=None) - await send_request_required_client(request) - - - request = explicit.build_post_optional_integer_property_request(json={"value": None}) - await send_request_required_client(request) - - request = explicit.build_post_optional_integer_header_request(header_parameter=None) - await send_request_required_client(request) - -@pytest.mark.asyncio -async def test_post_optional_string(send_request_required_client): - request = explicit.build_post_optional_string_parameter_request(content=None) - await send_request_required_client(request) - - - request = explicit.build_post_optional_string_property_request(json={"value": None}) - await send_request_required_client(request) - - request = explicit.build_post_optional_string_header_request(body_parameter=None) - await send_request_required_client(request) - -@pytest.mark.asyncio -async def test_post_optional_class(send_request_required_client): - request = explicit.build_post_optional_class_parameter_request() - await send_request_required_client(request) - - request = explicit.build_post_optional_class_property_request(json={"value": None}) - await send_request_required_client(request) - -@pytest.mark.asyncio -async def test_post_optional_array(send_request_required_client): - request = explicit.build_post_optional_array_parameter_request(json=None) - await send_request_required_client(request) - - request = explicit.build_post_optional_array_property_request(json={"value": None}) - await send_request_required_client(request) - - request = explicit.build_post_optional_array_header_request(header_parameter=None) - await send_request_required_client(request) - -@pytest.mark.asyncio -async def test_implicit_get_required(send_request_client): - with pytest.raises(ValueError): - request = implicit.build_get_required_path_request(path_parameter=None) - await send_request_client(request) - - with pytest.raises(ValueError): - request = implicit.build_get_required_global_path_request(required_global_path=None) - await send_request_client(request) - - with pytest.raises(ValueError): - request = implicit.build_get_required_global_query_request(required_global_query=None) - await send_request_client(request) - -@pytest.mark.asyncio -async def test_post_required_string(send_request_client): - with pytest.raises(ValueError): - request = explicit.build_post_required_string_header_request(header_parameter=None) - await send_request_client(request) - - with pytest.raises(HttpResponseError) as ex: - request = explicit.build_post_required_string_parameter_request(content=None) - await send_request_client(request) - - assert "Not Found" in str(ex.value) - - with pytest.raises(HttpResponseError)as ex: - request = explicit.build_post_required_string_property_request(json={"value": None}) - await send_request_client(request) - assert "Not Found" in str(ex.value) - -@pytest.mark.asyncio -async def test_post_required_array(send_request_client): - with pytest.raises(TypeError): - request = explicit.build_post_required_array_header_request(header_parameter=None) - await send_request_client(request) - - with pytest.raises(HttpResponseError) as ex: - request = explicit.build_post_required_array_parameter_request() - await send_request_client(request) - assert "Not Found" in str(ex.value) - - with pytest.raises(HttpResponseError) as ex: - request = explicit.build_post_required_array_property_request(json={"value": None}) - await send_request_client(request) - assert "Not Found" in str(ex.value) - -@pytest.mark.asyncio -async def test_post_required_class(send_request_client): - with pytest.raises(HttpResponseError) as ex: - request = explicit.build_post_required_class_parameter_request() - await send_request_client(request) - assert "Not Found" in str(ex.value) - - with pytest.raises(HttpResponseError) as ex: - request = explicit.build_post_required_class_property_request(json={"value": None}) - await send_request_client(request) - assert "Not Found" in str(ex.value) - -@pytest.mark.asyncio -async def test_explict_put_optional_binary_body(send_request_client): - request = explicit.build_put_optional_binary_body_request() - await send_request_client(request) - -@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') - with io.BytesIO(test_bytes) as stream_data: - request = explicit.build_put_required_binary_body_request(content=stream_data) - await client.send_request(request, stream=True) - -@pytest.mark.asyncio -async def test_implicit_put_optional_binary_body(send_request_client): - request = explicit.build_put_optional_binary_body_request() - await send_request_client(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_reserved_words.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_reserved_words.py deleted file mode 100644 index bed31633b69..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_reserved_words.py +++ /dev/null @@ -1,83 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from reservedwordslowlevel.aio import ReservedWordsClient -from reservedwordslowlevel.rest import import_operations -from reservedwordslowlevel.rest import ( - build_operation_with_files_param_request, - build_operation_with_data_param_request, - build_operation_with_json_param_request, - build_operation_with_content_param_request, - build_operation_with_url_request, -) - -@pytest.fixture -async def client(): - async with ReservedWordsClient() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_operation_group_import(send_request): - - request = import_operations.build_operation_one_request(parameter1="foo") - await send_request(request) - -@pytest.mark.asyncio -async def test_operation_with_content_param(send_request): - request = build_operation_with_content_param_request(content=b"hello, world", headers={"Content-Type": "application/octet-stream"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_operation_with_json_param(send_request): - request = build_operation_with_json_param_request(json={"hello": "world"}) - await send_request(request) - -@pytest.mark.skip("We don't do urlencoded bodies anymore") -@pytest.mark.asyncio -async def test_operation_with_data_param(send_request): - request = build_operation_with_data_param_request(data={"data": "hello", "world": "world"}) - await send_request(request) - -@pytest.mark.skip("We don't do multipart bodies anymore") -@pytest.mark.asyncio -async def test_operation_with_files_param(send_request): - request = build_operation_with_files_param_request(files={ - "file_name": "my.txt", - "files": b'bytes' - }) - await send_request(request) - -@pytest.mark.asyncio -async def test_operation_with_url(send_request): - request = build_operation_with_url_request("foo", header_parameters="x-ms-header", query_parameters=["one", "two"]) - await send_request(request) - diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_security.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_security.py deleted file mode 100644 index d9d969efb23..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_security.py +++ /dev/null @@ -1,53 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from securitykeyswaggerlowlevel.aio import AutorestSecurityKey -from securityaadswaggerlowlevel.aio import AutorestSecurityAad - -from azure.core.credentials import AzureKeyCredential -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): - from securityaadswaggerlowlevel.rest import build_head_request - - client = AutorestSecurityAad(credential=credential_async) - assert isinstance(client._config.authentication_policy, AsyncBearerTokenCredentialPolicy) - request = build_head_request() - response = await client.send_request(request, enforce_https=False) - response.raise_for_status() - -@pytest.mark.asyncio -async def test_security_key_swagger(): - from securitykeyswaggerlowlevel.rest import build_head_request - - # 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')) - assert isinstance(client._config.authentication_policy, AzureKeyCredentialPolicy) - request = build_head_request() - response = await client.send_request(request) - response.raise_for_status() diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_send_request.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_send_request.py deleted file mode 100644 index e9ad4a3457b..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_send_request.py +++ /dev/null @@ -1,173 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import io -import json -import pytest -from azure.core.rest import HttpRequest - -from os.path import dirname, pardir, join, realpath -import pytest - -cwd = dirname(realpath(__file__)) - -class TestSendRequest(object): - - @pytest.mark.asyncio - async def test_send_request_with_body_get_model_deserialize(self): - from bodycomplexlowlevel.aio import AutoRestComplexTestService - - client = AutoRestComplexTestService() - - request = HttpRequest("GET", "/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, - ) - - response = await client.send_request(request) - deserialized = response.json() - 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(self): - from bodycomplexlowlevel.aio import AutoRestComplexTestService - client = AutoRestComplexTestService() - - request = HttpRequest("GET", "/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, - ) - - async with client.send_request(request, stream=True) as response: - data = b'' - async for chunk in response.iter_bytes(): - data += chunk - json_response = json.loads(data.decode('utf-8')) - 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): - from bodycomplexlowlevel.aio import AutoRestComplexTestService - - client = AutoRestComplexTestService() - - siamese_body = { - "id": 2, - "name": "Siameeee", - "color": "green", - "hates": - [ - { - "id": 1, - "name": "Potato", - "food": "tomato" - }, - { - "id": -1, - "name": "Tomato", - "food": "french fries" - } - ], - "breed": "persian" - } - - request = HttpRequest("PUT", "/complex/inheritance/valid", - json=siamese_body, - ) - - response = await client.send_request(request) - assert response.status_code == 200 - - @pytest.mark.asyncio - async def test_send_request_get_stream(self): - from bodyfilelowlevel.aio import AutoRestSwaggerBATFileService - - client = AutoRestSwaggerBATFileService(connection_data_block_size=1000) - file_length = 0 - with io.BytesIO() as file_handle: - - request = HttpRequest("GET", "http://localhost:3000/files/stream/nonempty", - headers={ - 'Accept': 'image/png, application/json' - }, - ) - - async with client.send_request(request, stream=True) as response: - response.raise_for_status() - - async for data in response.iter_bytes(): - file_length += len(data) - file_handle.write(data) - - 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: - sample_data = hash(data.read()) - assert sample_data == hash(file_handle.getvalue()) - - @pytest.mark.asyncio - async def test_send_request_put_stream(self): - from bodyformdatalowlevel.aio import AutoRestSwaggerBATFormDataService - - client = AutoRestSwaggerBATFormDataService( - headers={"Content-Type": "application/octet-stream"} - ) - - test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') - with io.BytesIO(test_bytes) as stream_data: - request = HttpRequest("PUT", '/formdata/stream/uploadfile', - 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(self): - from bodycomplexlowlevel import AutoRestComplexTestService - - client = AutoRestComplexTestService(endpoint="http://fakeUrl") - - request = HttpRequest("GET", "http://localhost:3000/complex/inheritance/valid") - - response = client.send_request(request) - - deserialized = response.json() - assert 2 == deserialized['id'] - assert "Siameeee" == deserialized['name'] - assert -1 == deserialized['hates'][1]['id'] - assert "Tomato" == deserialized['hates'][1]['name'] diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_string_tests.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_string_tests.py deleted file mode 100644 index 6485380ab93..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_string_tests.py +++ /dev/null @@ -1,183 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from async_generator import yield_, async_generator -from azure.core.exceptions import HttpResponseError - -from bodystringlowlevel.aio import AutoRestSwaggerBATService -from bodystringlowlevel.rest import string, enum -import pytest -from bodystringlowlevel._serialization import Serializer, Deserializer -from base64 import b64decode - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestSwaggerBATService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@pytest.mark.asyncio -async def test_null(send_request): - request = string.build_get_null_request() - assert (await send_request(request)).text() == '' - - request = string.build_put_null_request(content=None) - await send_request(request) - -@pytest.mark.asyncio -async def test_empty(send_request, send_request_json_response): - request = string.build_get_empty_request() - assert "" == await send_request_json_response(request) - # changing this behavior because of this pr being merged: https://github.com/Azure/autorest.testserver/pull/145/files - request = string.build_put_empty_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_mbcs(send_request, send_request_json_response): - try: - test_str = ( - "\xe5\x95\x8a\xe9\xbd\x84\xe4\xb8\x82\xe7\x8b\x9b\xe7\x8b" - "\x9c\xef\xa7\xb1\xef\xa4\xac\xef\xa7\xb1\xef\xa8\x8c\xef" - "\xa8\xa9\xcb\x8a\xe3\x80\x9e\xe3\x80\xa1\xef\xbf\xa4\xe2" - "\x84\xa1\xe3\x88\xb1\xe2\x80\x90\xe3\x83\xbc\xef\xb9\xa1" - "\xef\xb9\xa2\xef\xb9\xab\xe3\x80\x81\xe3\x80\x93\xe2\x85" - "\xb0\xe2\x85\xb9\xe2\x92\x88\xe2\x82\xac\xe3\x88\xa0\xe3" - "\x88\xa9\xe2\x85\xa0\xe2\x85\xab\xef\xbc\x81\xef\xbf\xa3" - "\xe3\x81\x81\xe3\x82\x93\xe3\x82\xa1\xe3\x83\xb6\xce\x91" - "\xef\xb8\xb4\xd0\x90\xd0\xaf\xd0\xb0\xd1\x8f\xc4\x81\xc9" - "\xa1\xe3\x84\x85\xe3\x84\xa9\xe2\x94\x80\xe2\x95\x8b\xef" - "\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') - - except AttributeError: - test_str = ( - b"\xe5\x95\x8a\xe9\xbd\x84\xe4\xb8\x82\xe7\x8b\x9b\xe7\x8b" - b"\x9c\xef\xa7\xb1\xef\xa4\xac\xef\xa7\xb1\xef\xa8\x8c\xef" - b"\xa8\xa9\xcb\x8a\xe3\x80\x9e\xe3\x80\xa1\xef\xbf\xa4\xe2" - b"\x84\xa1\xe3\x88\xb1\xe2\x80\x90\xe3\x83\xbc\xef\xb9\xa1" - b"\xef\xb9\xa2\xef\xb9\xab\xe3\x80\x81\xe3\x80\x93\xe2\x85" - b"\xb0\xe2\x85\xb9\xe2\x92\x88\xe2\x82\xac\xe3\x88\xa0\xe3" - b"\x88\xa9\xe2\x85\xa0\xe2\x85\xab\xef\xbc\x81\xef\xbf\xa3" - b"\xe3\x81\x81\xe3\x82\x93\xe3\x82\xa1\xe3\x83\xb6\xce\x91" - b"\xef\xb8\xb4\xd0\x90\xd0\xaf\xd0\xb0\xd1\x8f\xc4\x81\xc9" - b"\xa1\xe3\x84\x85\xe3\x84\xa9\xe2\x94\x80\xe2\x95\x8b\xef" - 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') - - request = string.build_get_mbcs_request() - assert test_str == await send_request_json_response(request) - - request = string.build_put_mbcs_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_whitespace(send_request, send_request_json_response): - test_str = " Now is the time for all good men to come to the aid of their country " - request = string.build_get_whitespace_request() - assert test_str == await send_request_json_response(request) - - request = string.build_put_whitespace_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_get_not_provided(send_request): - request = string.build_get_not_provided_request() - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_enum_not_expandable(send_request, send_request_json_response): - request = enum.build_get_not_expandable_request() - assert "red color" == await send_request_json_response(request) - - request = enum.build_put_not_expandable_request(json='red color') - await send_request(request) - - request = enum.build_put_not_expandable_request(json='red color') - await send_request(request) - # 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. - - request = enum.build_put_not_expandable_request(json='not a color') - with pytest.raises(HttpResponseError): - await send_request(request) - -@pytest.mark.asyncio -async def test_get_base64_encoded(send_request): - request = string.build_get_base64_encoded_request() - assert b64decode((await send_request(request)).text()) == 'a string that gets encoded with base64'.encode() - -@pytest.mark.asyncio -async def test_base64_url_encoded(send_request): - # the b64 encoding and decoding is taken from msrest - request = string.build_get_base64_url_encoded_request() - response = (await send_request(request)).text() - response = Deserializer.deserialize_base64(response) - assert response == 'a string that gets encoded with base64url'.encode() - - content = Serializer.serialize_base64('a string that gets encoded with base64url'.encode()) - request = string.build_put_base64_url_encoded_request(json=content) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_null_base64_url_encoded(send_request): - request = string.build_get_null_base64_url_encoded_request() - assert (await send_request(request)).text() == '' - -@pytest.mark.asyncio -async def test_enum_referenced(send_request, send_request_json_response): - request = enum.build_put_referenced_request(json='red color') - await send_request(request) - - request = enum.build_put_referenced_request(json="red color") - await send_request(request) - - request = enum.build_get_referenced_request() - assert await send_request_json_response(request) == 'red color' - -@pytest.mark.asyncio -async def test_enum_referenced_constant(send_request, send_request_json_response): - request = enum.build_put_referenced_request(json="red color") - await send_request(request) - - request = enum.build_get_referenced_constant_request() - assert await send_request_json_response(request) == {'field1': 'Sample String'} # there's no constant on the response, so just getting field1 diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_time.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_time.py deleted file mode 100644 index 01b4369f75c..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_time.py +++ /dev/null @@ -1,54 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import datetime -from async_generator import yield_, async_generator - -from bodytimelowlevel.aio import AutoRestTimeTestService -from bodytimelowlevel.rest import time -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestTimeTestService() as client: - await yield_(client) - -@pytest.mark.asyncio -async def test_get(client): - request = time.build_get_request() - response = await client.send_request(request) - response.raise_for_status() - assert datetime.datetime.strptime(response.json(), '%H:%M:%S').time() == datetime.time(11, 34, 56) - - -@pytest.mark.asyncio -async def test_put(client): - request = time.build_put_request(json=datetime.time(8, 7, 56).strftime("%H:%M:%S")) - response = await client.send_request(request) - response.raise_for_status() - assert response.json() == "Nice job posting time" diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_url.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_url.py deleted file mode 100644 index 3dd2a0c029e..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_url.py +++ /dev/null @@ -1,393 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from datetime import datetime -from async_generator import yield_, async_generator -from urllowlevel.aio import AutoRestUrlTestService -from urllowlevel.rest import path_items, paths, queries -from urlmulticollectionformatlowlevel.aio import AutoRestUrlMutliCollectionFormatTestService -from urlmulticollectionformatlowlevel.rest import queries as multi_queries - -import pytest - -@pytest.fixture -@async_generator -async def 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 send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def make_multi_request(multi_client, base_send_request): - async def _send_request(request): - return await base_send_request(multi_client, request) - return _send_request - -@pytest.fixture -@pytest.mark.asyncio -async def test_array_query(): - return ["ArrayQuery1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] - -@pytest.mark.asyncio -async def test_byte_empty_and_null(send_request): - request = paths.build_byte_empty_request() - await send_request(request) - - with pytest.raises(ValueError): - paths.build_byte_null_request(None) - -@pytest.mark.asyncio -async def test_byte_multi_byte(send_request): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') - request = paths.build_byte_multi_byte_request(u_bytes) - await send_request(request) - -@pytest.mark.asyncio -async def test_date_null(send_request): - with pytest.raises(ValueError): - paths.build_date_null_request(None) - -@pytest.mark.asyncio -async def test_date_time_null(send_request): - with pytest.raises(ValueError): - paths.build_date_time_null_request(None) - -@pytest.mark.asyncio -async def test_date_time_valid(send_request): - request = paths.build_date_time_valid_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_date_valid(send_request): - request = paths.build_date_valid_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_unix_time_url(send_request): - request = paths.build_unix_time_url_request(datetime(year=2016, month=4, day=13)) - await send_request(request) - -@pytest.mark.asyncio -async def test_double_decimal(send_request): - request = paths.build_double_decimal_negative_request() - await send_request(request) - request = paths.build_double_decimal_positive_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_float_scientific(send_request): - request = paths.build_float_scientific_negative_request() - await send_request(request) - - request = paths.build_float_scientific_positive_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_get_boolean(send_request): - request = paths.build_get_boolean_false_request() - await send_request(request) - - request = paths.build_get_boolean_true_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_int(send_request): - request = paths.build_get_int_negative_one_million_request() - await send_request(request) - - request = paths.build_get_int_one_million_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_get_long(send_request): - request = paths.build_get_negative_ten_billion_request() - await send_request(request) - - request = paths.build_get_ten_billion_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_string_empty_and_null(send_request): - request = paths.build_string_empty_request() - await send_request(request) - - with pytest.raises(ValueError): - paths.build_string_null_request(None) - -@pytest.mark.asyncio -async def test_array_csv_in_path(send_request): - test_array = ["ArrayPath1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] - request = paths.build_array_csv_in_path_request(test_array) - await send_request(request) - -@pytest.mark.asyncio -async def test_string_url_encoded(send_request): - request = paths.build_string_url_encoded_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_paths_unicode(send_request): - request = paths.build_string_unicode_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_string_url_non_encoded(send_request): - request = paths.build_string_url_non_encoded_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_enum_valid(send_request): - request = paths.build_enum_valid_request("green color") - await send_request(request) - -@pytest.mark.asyncio -async def test_enum_null(send_request): - with pytest.raises(ValueError): - paths.build_enum_null_request(None) - -@pytest.mark.asyncio -async def test_base64_url(send_request): - request = paths.build_base64_url_request("lorem".encode()) - await send_request(request) - -@pytest.mark.asyncio -async def test_queries_byte(send_request): - request = queries.build_byte_empty_request() - await send_request(request) - - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') - request = queries.build_byte_multi_byte_request(byte_query=u_bytes) - await send_request(request) - - request = queries.build_byte_null_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_queries_date(send_request): - request = queries.build_date_null_request() - await send_request(request) - - request = queries.build_date_valid_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_queries_date_time(send_request): - request = queries.build_date_time_null_request() - await send_request(request) - - request = queries.build_date_time_valid_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_queries_double(send_request): - request = queries.build_double_null_request() - await send_request(request) - - request = queries.build_double_decimal_negative_request() - await send_request(request) - - request = queries.build_double_decimal_positive_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_queries_float_scientific(send_request): - request = queries.build_float_scientific_negative_request() - await send_request(request) - - request = queries.build_float_scientific_positive_request() - await send_request(request) - request = queries.build_float_null_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_queries_boolean(send_request): - request = queries.build_get_boolean_false_request() - await send_request(request) - - request = queries.build_get_boolean_true_request() - await send_request(request) - - request = queries.build_get_boolean_null_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_queries_int(send_request): - request = queries.build_get_int_negative_one_million_request() - await send_request(request) - - request = queries.build_get_int_one_million_request() - await send_request(request) - - request = queries.build_get_int_null_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_queries_long(send_request): - request = queries.build_get_negative_ten_billion_request() - await send_request(request) - - request = queries.build_get_ten_billion_request() - await send_request(request) - - request = queries.build_get_long_null_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_queries_string(send_request): - request = queries.build_string_empty_request() - await send_request(request) - - request = queries.build_string_null_request() - await send_request(request) - - request = queries.build_string_url_encoded_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_queries_enum(send_request): - request = queries.build_enum_valid_request(enum_query="green color") - await send_request(request) - - request = queries.build_enum_null_request(enum_query=None) - await send_request(request) - -@pytest.mark.asyncio -async def test_queries_unicode(send_request): - request = queries.build_string_unicode_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_array_string_csv(send_request, test_array_query): - request = queries.build_array_string_csv_empty_request(array_query=[]) - await send_request(request) - - request = queries.build_array_string_csv_null_request(array_query=None) - await send_request(request) - - request = queries.build_array_string_csv_valid_request(array_query=test_array_query) - await send_request(request) - -@pytest.mark.asyncio -async def test_array_string_miscellaneous(send_request, test_array_query): - request = queries.build_array_string_pipes_valid_request(array_query=test_array_query) - await send_request(request) - - request = queries.build_array_string_ssv_valid_request(array_query=test_array_query) - await send_request(request) - -@pytest.mark.asyncio -@pytest.mark.skip(reason="https://github.com/aio-libs/aiohttp/issues/5904") -async def test_array_string_tsv_valid(send_request, test_array_query): - request = queries.build_array_string_tsv_valid_request(array_query=test_array_query) - await send_request(request) - -@pytest.mark.asyncio -async def test_array_string_multi(make_multi_request, test_array_query): - request = multi_queries.build_array_string_multi_empty_request(array_query=[]) - await make_multi_request(request) - - request = multi_queries.build_array_string_multi_null_request() - await make_multi_request(request) - - request = multi_queries.build_array_string_multi_valid_request(array_query=test_array_query) - await make_multi_request(request) - -@pytest.mark.asyncio -async def test_array_string_no_collection_format(send_request): - request = queries.build_array_string_no_collection_format_empty_request(array_query=['hello', 'nihao', 'bonjour']) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_all_with_values(send_request): - # In LLC, we have to pass in global variables to individual operations; we don't have access to the client in the request builders - global_string_path = "globalStringPath" - global_string_query = "globalStringQuery" - - request = path_items.build_get_all_with_values_request( - path_item_string_path="pathItemStringPath", - global_string_path=global_string_path, - local_string_path="localStringPath", - path_item_string_query="pathItemStringQuery", - global_string_query=global_string_query, - local_string_query="localStringQuery", - ) - - await send_request(request) - -@pytest.mark.asyncio -async def test_get_global_and_local_query_null(send_request): - # In LLC, we have to pass in global variables to individual operations; we don't have access to the client in the request builders - global_string_path = "globalStringPath" - - request = path_items.build_get_global_and_local_query_null_request( - path_item_string_path="pathItemStringPath", - global_string_path=global_string_path, - local_string_path="localStringPath", - path_item_string_query="pathItemStringQuery", - global_string_query=None - ) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_global_query_null(send_request): - # In LLC, we have to pass in global variables to individual operations; we don't have access to the client in the request builders - global_string_path = "globalStringPath" - - request = path_items.build_get_global_query_null_request( - path_item_string_path="pathItemStringPath", - global_string_path=global_string_path, - local_string_path="localStringPath", - path_item_string_query="pathItemStringQuery", - local_string_query="localStringQuery", - ) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_local_path_item_query_null(send_request): - # In LLC, we have to pass in global variables to individual operations; we don't have access to the client in the request builders - global_string_path = "globalStringPath" - global_string_query = "globalStringQuery" - - request = path_items.build_get_local_path_item_query_null_request( - path_item_string_path="pathItemStringPath", - global_string_path=global_string_path, - local_string_path="localStringPath", - path_item_string_query=None, - global_string_query=global_string_query, - local_string_query=None, - ) - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_urlencoded.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_urlencoded.py deleted file mode 100644 index 4b1bcf706d6..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_urlencoded.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from bodyformurlencodeddatalowlevel.aio import BodyFormsDataURLEncoded -from bodyformurlencodeddatalowlevel.rest import formdataurlencoded - -@pytest.fixture -async def client(): - async with BodyFormsDataURLEncoded() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.mark.skip("We don't do urlencoded bodies anymore.") -@pytest.mark.asyncio -async def test_update_pet_with_form(send_request): - request = formdataurlencoded.build_update_pet_with_form_request( - pet_id=1, - data={ - "pet_type": "dog", - "pet_food": "meat", - "pet_age": 42, - "name": "Fido", - } - ) - await send_request(request) - -@pytest.mark.skip("We don't do urlencoded bodies anymore.") -@pytest.mark.asyncio -async def test_partial_constant_body(send_request): - request = formdataurlencoded.build_partial_constant_body_request( - data={ - "access_token": "foo", - "grant_type": "access_token", - "service": "bar" - } - ) - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_validation.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_validation.py deleted file mode 100644 index 4a69d6f2da4..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_validation.py +++ /dev/null @@ -1,94 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import sys - -from azure.core.exceptions import HttpResponseError -from async_generator import yield_, async_generator - -from validationlowlevel.aio import AutoRestValidationTest -from validationlowlevel.rest import * - -import pytest - -@pytest.fixture -@async_generator -async def client(): - async with AutoRestValidationTest( - "abc123", - ) as client: - client.api_version = "12-34-5678" - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - async def _send_request(request): - return await base_send_request_json_response(client, request) - return _send_request - -@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 { - 'child': { - 'constProperty': 'constant' - }, - 'constChild': { - 'constProperty': 'constant', - 'constProperty2': 'constant2' - }, - 'constInt': 0, - 'constString': 'constant', - 'constStringAsEnum': 'constant_string_as_enum' - } - -@pytest.mark.asyncio -async def test_with_constant_in_path(send_request): - request = build_get_with_constant_in_path_request() - await send_request(request) - -@pytest.mark.asyncio -async def test_post_with_constant_in_body(send_request_json_response, constant_body): - request = build_post_with_constant_in_body_request(json=constant_body) - product = await send_request_json_response(request) - assert product is not None - -# 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 HttpResponseError -@pytest.mark.asyncio -async def test_fakedpath_validation(send_request): - with pytest.raises(HttpResponseError): - request = build_validation_of_method_parameters_request(subscription_id="abc123", resource_group_name="1", id=100) - await send_request(request) - \ No newline at end of file diff --git a/test/vanilla/low-level/AcceptanceTests/asynctests/test_xml.py b/test/vanilla/low-level/AcceptanceTests/asynctests/test_xml.py deleted file mode 100644 index 4cfbed6648f..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/asynctests/test_xml.py +++ /dev/null @@ -1,262 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from async_generator import yield_, async_generator - -from xmlservicelowlevel.aio import AutoRestSwaggerBATXMLService - -import xml.etree.ElementTree as ET -from xmlservicelowlevel.rest import xml -from base64 import b64decode - -import pytest -@pytest.fixture -@async_generator -async def client(): - async with AutoRestSwaggerBATXMLService() as client: - await yield_(client) - -@pytest.fixture -def send_request(client, base_send_request): - async def _send_request(request): - return await base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_text_response(client, base_send_request): - async def _send_request(request): - return (await base_send_request(client, request)).text() - return _send_request - - - -@pytest.mark.asyncio -async def test_json_xml(send_request, send_request_text_response): - request = xml.build_json_input_request(json={"id": 42}) - await send_request(request) - - request = xml.build_json_output_request() - assert (await send_request(request)).json()['id'] == 42 - -@pytest.mark.asyncio -async def test_simple(send_request, send_request_text_response): - # Slideshow - - request = xml.build_get_simple_request() - slideshow = ET.fromstring(await send_request_text_response(request)) - assert slideshow.attrib['title'] == "Sample Slide Show" - assert slideshow.attrib['date'] == "Date of publication" - assert slideshow.attrib['author'] == "Yours Truly" - slides = list(slideshow.iterfind('slide')) - assert len(slides) == 2 - - slide1 = slides[0] - assert slide1.attrib['type'] == "all" - assert next(slide1.iterfind('title')).text == "Wake up to WonderWidgets!" - assert len(list(slide1.iterfind('item'))) == 0 - - slide2 = slides[1] - assert slide2.attrib['type'] == "all" - assert next(slide2.iterfind('title')).text == "Overview" - items = list(slide2.iterfind('item')) - assert len(items) == 3 - assert items[0].text == "Why WonderWidgets are great" - assert items[1].text == None - assert items[2].text == "Who buys WonderWidgets" - - request = xml.build_put_simple_request(content=slideshow, headers={"Content-Type": "application/xml"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_empty_child_element(send_request, send_request_text_response): - request = xml.build_get_empty_child_element_request() - banana = ET.fromstring(await send_request_text_response(request)) - assert banana.attrib == {}# That's the point of this test, it was an empty node. - request = xml.build_put_empty_child_element_request(content=banana, headers={"Content-Type": "application/xml"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_empty_root_list(send_request, send_request_text_response): - request = xml.build_get_empty_root_list_request() - empty = ET.fromstring(await send_request_text_response(request)) - assert empty.tag == 'bananas' - assert empty.attrib == {} - assert await send_request_text_response(request) == "\n" - request = xml.build_put_empty_root_list_request(content=empty, headers={"Content-Type": "application/xml"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_root_list_single_item(send_request, send_request_text_response): - request = xml.build_get_root_list_single_item_request() - xml_body = ET.fromstring(await send_request_text_response(request)) - bananas = list(xml_body.iterfind('banana')) - assert len(bananas) == 1 - assert next(bananas[0].iterfind('name')).text == "Cavendish" - request = xml.build_put_root_list_single_item_request(content=xml_body, headers={"Content-Type": "application/xml"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_root_list(send_request, send_request_text_response): - request = xml.build_get_root_list_request() - xml_body = ET.fromstring(await send_request_text_response(request)) - bananas = list(xml_body.iterfind('banana')) - assert len(bananas) == 2 - request = xml.build_put_root_list_request(content=xml_body, headers={"Content-Type": "application/xml"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_empty_wrapped_lists(send_request, send_request_text_response): - request = xml.build_get_empty_wrapped_lists_request() - bananas = ET.fromstring(await send_request_text_response(request)) - """ - - - - `; - """ - good_apples = [a for a in bananas.iterfind('GoodApples') if a.text] - assert len(good_apples) == 0 - bad_apples = [a for a in bananas.iterfind('BadApples') if a.text] - assert len(bad_apples) == 0 - request = xml.build_put_empty_wrapped_lists_request(content=bananas, headers={"Content-Type": "application/xml"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_get_empty(send_request, send_request_text_response): - request = xml.build_get_empty_list_request() - slideshow = ET.fromstring(await send_request_text_response(request)) - request = xml.build_put_empty_list_request(content=slideshow, headers={"Content-Type": "application/xml"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_wrapped_lists(send_request, send_request_text_response): - request = xml.build_get_wrapped_lists_request() - bananas = ET.fromstring(await send_request_text_response(request)) - good_apples = bananas.find('GoodApples') - assert [a.text for a in good_apples.iterfind('Apple')] == ['Fuji', 'Gala'] - - bad_apples = bananas.find('BadApples') - assert [a.text for a in bad_apples.iterfind('Apple')] == ['Red Delicious'] - request = xml.build_put_wrapped_lists_request(content=bananas, headers={"Content-Type": "application/xml"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_complex_types(send_request, send_request_text_response): - request = xml.build_get_complex_type_ref_no_meta_request() - root = ET.fromstring(await send_request_text_response(request)) - ref_to_model = root.find('RefToModel') - assert ref_to_model.find('ID').text == "myid" - request = xml.build_put_complex_type_ref_no_meta_request(content=root, headers={"Content-Type": "application/xml"}) - await send_request(request) - - request = xml.build_get_complex_type_ref_with_meta_request() - root = ET.fromstring(await send_request_text_response(request)) - ref_to_model = root.find('XMLComplexTypeWithMeta') - assert ref_to_model.find('ID').text == "myid" - request = xml.build_put_complex_type_ref_with_meta_request(content=root, headers={"Content-Type": "application/xml"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_list_containers(send_request, send_request_text_response): - request = xml.build_list_containers_request() - xml_body = ET.fromstring(await send_request_text_response(request)) - containers = xml_body.find('Containers') - container_list = list(containers.iterfind('Container')) - assert len(container_list) == 3 - -@pytest.mark.asyncio -async def test_list_blobs(send_request, send_request_text_response): - request = xml.build_list_blobs_request() - xml_body = ET.fromstring(await send_request_text_response(request)) - blobs_xml_body = xml_body.find('Blobs') - blobs = list(blobs_xml_body.iterfind('Blob')) - assert len(blobs) == 5 - assert blobs_xml_body.find('BlobPrefix') is None - blob = blobs[0] - assert blob.find('Name').text == "blob1.txt" - properties = blob.find('Properties') - assert properties.find('Last-Modified').text == 'Wed, 09 Sep 2009 09:20:02 GMT' - assert properties.find('Etag').text == "0x8CBFF45D8A29A19" - assert properties.find('Content-Length').text == "100" - assert properties.find('Content-Type').text == "text/html" - # Check that an empty field in the XML is empty string - assert properties.find('Content-Encoding').text is None - assert properties.find('Content-Language').text == "en-US" - assert properties.find('Content-MD5').text is None - assert properties.find('Cache-Control').text == "no-cache" - assert properties.find('BlobType').text == "BlockBlob" - # Check that a field NOT in the XML is None - assert properties.find('Destination-Snapshot') is None - metadata_body = blob.find('Metadata') - assert metadata_body.find("Color").text == "blue" - assert metadata_body.find("BlobNumber").text == "01" - assert metadata_body.find("SomeMetadataName").text == "SomeMetadataValue" - -@pytest.mark.asyncio -async def test_service_properties(send_request, send_request_text_response): - request = xml.build_get_service_properties_request() - properties = ET.fromstring(await send_request_text_response(request)) - assert properties.find('HourMetrics') is not None - assert properties.find('MinuteMetrics') is not None - request = xml.build_put_service_properties_request(content=properties, headers={"Content-Type": "application/xml"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_acls(send_request, send_request_text_response): - request = xml.build_get_acls_request() - acls = ET.fromstring(await send_request_text_response(request)) - signed_identifiers = list(acls.iterfind('SignedIdentifier')) - assert len(signed_identifiers) == 1 - assert signed_identifiers[0].find('Id').text == 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=' - request = xml.build_put_acls_request(content=acls, headers={"Content-Type": "application/xml"}) - await send_request(request) - - -@pytest.mark.asyncio -async def test_xms_text(send_request, send_request_text_response): - request = xml.build_get_xms_text_request() - xml_object = ET.fromstring(await send_request_text_response(request)) - assert xml_object.attrib['language'] == "english" - assert xml_object.text == "I am text" - -@pytest.mark.asyncio -async def test_bytes(send_request, send_request_text_response): - request = xml.build_get_bytes_request() - bytes_object = ET.fromstring(await send_request_text_response(request)) - assert bytes_object.tag == 'ModelWithByteProperty' - assert b64decode(bytes_object.find('Bytes').text) == b"Hello world" - - request = xml.build_put_binary_request(content=bytes_object, headers={"Content-Type": "application/xml"}) - await send_request(request) - -@pytest.mark.asyncio -async def test_url(send_request, send_request_text_response): - request = xml.build_get_uri_request() - url_object = ET.fromstring(await send_request_text_response(request)) - assert url_object.tag == 'ModelWithUrlProperty' - assert url_object.find('Url').text == 'https://myaccount.blob.core.windows.net/' - - request = xml.build_put_uri_request(content=url_object, headers={"Content-Type": "application/xml"}) - await send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/conftest.py b/test/vanilla/low-level/AcceptanceTests/conftest.py deleted file mode 100644 index ec929e9c7c5..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/conftest.py +++ /dev/null @@ -1,123 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import glob -import sys -import subprocess -import os -import signal -from os.path import dirname, realpath -from unittest import TestLoader, TextTestRunner - -from os.path import dirname, pardir, join, realpath - -from azure.core.pipeline.policies import SansIOHTTPPolicy -from azure.core.credentials import AccessToken - -import pytest - - -cwd = dirname(realpath(__file__)) - -#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 - return subprocess.Popen(cmd) - - 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 -def terminate_server_process(process): - 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.""" - server = start_server_process() - yield - terminate_server_process(server) - -@pytest.fixture() -def base_send_request(): - def send_request(client, request): - response = client.send_request(request) - response.raise_for_status() - return response - return send_request - -@pytest.fixture() -def base_send_request_json_response(): - def send_request_json_response(client, request): - response = client.send_request(request) - response.raise_for_status() - return response.json() - return send_request_json_response - -class CookiePolicy(SansIOHTTPPolicy): - def __init__(self, *args, **kwargs): - self._current_cookie = None - - def on_request(self, request, **kwargs): - # type: (PipelineRequest, Any) -> None - http_request = request.http_request - if self._current_cookie: - http_request.headers["Cookie"] = self._current_cookie - self._current_cookie = None - - def on_response(self, request, response, **kwargs): - # type: (PipelineRequest, PipelineResponse, Any) -> None - http_response = response.http_response - - 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) - -@pytest.fixture() -def credential(): - 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/test/vanilla/low-level/AcceptanceTests/test_additional_properties.py b/test/vanilla/low-level/AcceptanceTests/test_additional_properties.py deleted file mode 100644 index 5e645acd2b9..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_additional_properties.py +++ /dev/null @@ -1,127 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from additionalpropertieslowlevel import AdditionalPropertiesClient -from additionalpropertieslowlevel.rest import pets - -@pytest.fixture -def client(): - with AdditionalPropertiesClient() as client: - yield client - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_create_ap_true(send_request_json_response): - json = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - }, - "id": 1, - "name": "Puppy", - } - request = pets.build_create_ap_true_request(json=json) - response = send_request_json_response(request) - assert response["birthdate"] == '2017-12-13T02:29:51Z' - -def test_create_cat_ap_true(send_request_json_response): - json = { - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': {'color': 'Red'}, - 'id': 1, - 'name': 'Lisa', - 'friendly': True - } - request = pets.build_create_cat_ap_true_request(json=json) - response = send_request_json_response(request) - assert response['birthdate'] == '2017-12-13T02:29:51Z' - -def test_create_ap_object(send_request_json_response): - json = { - "id": 2, - "name": "Hira", - 'siblings': [{ - 'id': 1, - 'name': 'Puppy', - 'birthdate': '2017-12-13T02:29:51Z', - 'complexProperty': { - 'color': 'Red' - } - }], - 'picture': '//////4=' - } - request = pets.build_create_ap_object_request(json=json) - response = send_request_json_response(request) - assert response['siblings'][0]['birthdate'] == '2017-12-13T02:29:51Z' - -def test_create_ap_string(send_request_json_response): - json = { - "id": 3, - "name": 'Tommy', - 'color': 'red', - 'weight': '10 kg', - 'city': 'Bombay' - } - request = pets.build_create_ap_string_request(json=json) - response = send_request_json_response(request) - assert response['color'] == 'red' - -def test_create_ap_in_properties(send_request_json_response): - json = { - "id": 4, - "name": 'Bunny', - "additionalProperties": { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } - } - request = pets.build_create_ap_in_properties_request(json=json) - response = send_request_json_response(request) - assert response["additionalProperties"]['weight'] == 599 - -def test_create_ap_in_properties_with_ap_string(send_request_json_response): - json = { - "id": 5, - "name": 'Funny', - "@odata.location":'westus', - 'color': 'red', - 'city': 'Seattle', - 'food': 'tikka masala', - "additionalProperties": { - 'height': 5.61, - 'weight': 599, - 'footsize': 11.5 - } - } - request = pets.build_create_ap_in_properties_with_ap_string_request(json=json) - response = send_request_json_response(request) - assert response['color'] == 'red' - assert response['additionalProperties']['weight'] == 599 \ No newline at end of file diff --git a/test/vanilla/low-level/AcceptanceTests/test_anything.py b/test/vanilla/low-level/AcceptanceTests/test_anything.py deleted file mode 100644 index c3d1796b1c3..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_anything.py +++ /dev/null @@ -1,68 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from anythinglowlevel import AnythingClient, rest - -@pytest.fixture -def client(): - with AnythingClient() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_get_string(send_request_json_response): - request = rest.build_get_string_request() - assert send_request_json_response(request) == 'anything' - -def test_put_string(send_request): - request = rest.build_put_string_request(json="anything") - send_request(request) - -def test_get_object(send_request_json_response): - request = rest.build_get_object_request() - assert send_request_json_response(request) == {"message": "An object was successfully returned"} - -def test_put_object(send_request): - request = rest.build_put_object_request(json={'foo': 'bar'}) - send_request(request) - -def test_get_array(send_request_json_response): - request = rest.build_get_array_request() - assert send_request_json_response(request) == ['foo', 'bar'] - -def test_put_array(send_request): - request = rest.build_put_array_request(json=['foo', 'bar']) - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_array.py b/test/vanilla/low-level/AcceptanceTests/test_array.py deleted file mode 100644 index 21e5bece273..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_array.py +++ /dev/null @@ -1,370 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import json -import isodate -from datetime import date, datetime, timedelta -from base64 import b64encode -from bodyarraylowlevel import AutoRestSwaggerBATArrayService -from bodyarraylowlevel.rest import array -from bodyarraylowlevel._serialization import Serializer, Deserializer -from azure.core.exceptions import DecodeError -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") - datetime2 = isodate.parse_datetime("1980-01-02T00:11:35Z") - 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"}] - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -@pytest.fixture -def serializer(): - return Serializer() - -@pytest.fixture -def deserializer(): - return Deserializer() - - -def test_empty(send_request, send_request_json_response): - request = array.build_get_empty_request() - - assert [] == send_request_json_response(request) - - request = array.build_get_null_request() - response = send_request(request) - assert response.text() == '' - - request = array.build_put_empty_request(json=[]) - send_request(request) - -def test_boolean_tfft(send_request, send_request_json_response): - request = array.build_get_boolean_tfft_request() - assert [True, False, False, True] == send_request_json_response(request) - request = array.build_put_boolean_tfft_request(json=[True, False, False, True]) - send_request(request) - -def test_integer_valid(send_request, send_request_json_response): - request = array.build_get_integer_valid_request() - assert [1, -1, 3, 300] == send_request_json_response(request) - request = array.build_put_integer_valid_request(json=[1, -1, 3, 300]) - send_request(request) - -def test_long_valid(send_request, send_request_json_response): - request = array.build_get_long_valid_request() - assert [1, -1, 3, 300] == send_request_json_response(request) - request = array.build_put_long_valid_request(json=[1, -1, 3, 300]) - send_request(request) - -def test_float_valid(send_request, send_request_json_response): - request = array.build_get_float_valid_request() - assert [0, -0.01, -1.2e20] == send_request_json_response(request) - request = array.build_put_float_valid_request(json=[0, -0.01, -1.2e20]) - send_request(request) - -def test_double_valid(send_request, send_request_json_response): - request = array.build_get_double_valid_request() - assert [0, -0.01, -1.2e20] == send_request_json_response(request) - request = array.build_put_double_valid_request(json=[0, -0.01, -1.2e20]) - send_request(request) - -def test_string_valid(send_request, send_request_json_response): - request = array.build_get_string_valid_request() - assert ["foo1", "foo2", "foo3"] == send_request_json_response(request) - request = array.build_put_string_valid_request(json=["foo1", "foo2", "foo3"]) - send_request(request) - -def test_get_string_with_null(send_request_json_response): - request = array.build_get_string_with_null_request() - assert ["foo", None, "foo2"] == send_request_json_response(request) - -def test_get_string_with_invalid(send_request_json_response): - request = array.build_get_string_with_invalid_request() - - # response differs from convenience layer - # this is bc in convenence layer we tell the deserializer to deserialize it fully as a list of string - assert ["foo", 123, "foo2"] == send_request_json_response(request) - -def test_uuid_valid(send_request, send_request_json_response): - request = array.build_get_uuid_valid_request() - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"] == send_request_json_response(request) - request = array.build_put_uuid_valid_request(json=["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "d1399005-30f7-40d6-8da6-dd7c89ad34db", - "f42f6aa1-a5bc-4ddf-907e-5f915de43205"]) - send_request(request) - -def test_get_uuid_invalid_chars(send_request, send_request_json_response): - #Handles invalid characters without error because of no guid class - request = array.build_get_uuid_invalid_chars_request() - assert ["6dcc7237-45fe-45c4-8a6b-3a8a3f625652", "foo"] == send_request_json_response(request) - -def test_date_valid(send_request, send_request_json_response): - def datetime_handler(x): - if isinstance(x, datetime.date): - return x.isoformat() - raise TypeError("Unknown type") - date1 = isodate.parse_date("2000-12-01") - date2 = isodate.parse_date("1980-01-02") - date3 = isodate.parse_date("1492-10-12") - - request = array.build_get_date_valid_request() - assert send_request_json_response(request), [date1, date2 == date3] - request = array.build_put_date_valid_request(json=[str(date1), str(date2), str(date3)]) # dates are not json serializable - send_request(request) - -def test_date_time_valid(send_request, send_request_json_response, datetimes, serializer): - request = array.build_get_date_time_valid_request() - - assert send_request_json_response(request), [datetimes[0], datetimes[1] == datetimes[2]] - request = array.build_put_date_time_valid_request(json=[serializer.serialize_iso(datetime) for datetime in datetimes]) - send_request(request) - -def test_date_time_rfc1123_valid(send_request, send_request_json_response, datetimes, serializer): - request = array.build_get_date_time_rfc1123_valid_request() - assert send_request_json_response(request), [datetimes[0], datetimes[1] == datetimes[2]] - request = array.build_put_date_time_rfc1123_valid_request(json=[serializer.serialize_rfc(datetime) for datetime in datetimes]) - send_request(request) - -def test_duration_valid(send_request, send_request_json_response): - duration1 = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) - duration2 = timedelta(days=5, hours=1) - - request = array.build_get_duration_valid_request() - assert send_request_json_response(request), [duration1 == duration2] - request = array.build_put_duration_valid_request(json=[isodate.duration_isoformat(duration1), isodate.duration_isoformat(duration2)]) - send_request(request) - -def test_byte_valid(send_request, send_request_json_response): - bytes1 = bytearray([0x0FF, 0x0FF, 0x0FF, 0x0FA]) - bytes2 = bytearray([0x01, 0x02, 0x03]) - bytes3 = bytearray([0x025, 0x029, 0x043]) - - request = array.build_get_byte_valid_request() - assert send_request_json_response(request), [bytes1, bytes2 == bytes3] - request = array.build_put_byte_valid_request(json=[b64encode(b).decode() for b in [bytes1, bytes2, bytes3]]) - send_request(request) - -def test_get_byte_invalid_null(send_request_json_response): - request = array.build_get_byte_invalid_null_request() - assert send_request_json_response(request), [bytearray([0x0AB, 0x0AC, 0x0AD]) == None] - -def test_get_complex_null(send_request): - request = array.build_get_complex_null_request() - assert send_request(request).text() == '' - -def test_get_complex_empty(send_request_json_response): - request = array.build_get_complex_empty_request() - assert [] == send_request_json_response(request) - -def test_complex_valid(send_request, send_request_json_response, products): - request = array.build_get_complex_valid_request() - assert products == send_request_json_response(request) - request = array.build_put_complex_valid_request(json=products) - send_request(request) - -def test_get_array_valid(send_request, send_request_json_response): - listlist = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"]] - request = array.build_get_array_valid_request() - assert listlist == send_request_json_response(request) - request = array.build_put_array_valid_request(json=listlist) - send_request(request) - - -def test_dictionary_valid(send_request, send_request_json_response, listdict): - request = array.build_get_dictionary_valid_request() - assert listdict == send_request_json_response(request) - request = array.build_put_dictionary_valid_request(json=listdict) - send_request(request) - -def test_get_complex_item_null(send_request_json_response, products): - products_null = [products[0], None, products[2]] - request = array.build_get_complex_item_null_request() - assert products_null == send_request_json_response(request) - -def test_get_complex_item_empty(send_request_json_response, products): - products_empty = [products[0], {}, products[2]] - - request = array.build_get_complex_item_empty_request() - assert products_empty == send_request_json_response(request) - -def test_get_array_null(send_request): - request = array.build_get_array_null_request() - assert send_request(request).text() == '' - -def test_get_array_empty(send_request_json_response): - request = array.build_get_array_empty_request() - assert [] == send_request_json_response(request) - -def test_get_array_item_null(send_request_json_response): - listlist2 = [["1", "2", "3"], None, ["7", "8", "9"]] - request = array.build_get_array_item_null_request() - assert listlist2 == send_request_json_response(request) - -def test_get_array_item_empty(send_request_json_response): - listlist3 = [["1", "2", "3"], [], ["7", "8", "9"]] - request = array.build_get_array_item_empty_request() - assert listlist3 == send_request_json_response(request) - -def test_get_dictionary_and_dictionary_item_null(send_request, send_request_json_response, listdict): - - request = array.build_get_dictionary_null_request() - assert send_request(request).text() == '' - - listdict[1] = None - request = array.build_get_dictionary_item_null_request() - assert listdict == send_request_json_response(request) - -def test_get_dictionary_and_dictionary_item_empty(send_request_json_response, listdict): - request = array.build_get_dictionary_empty_request() - assert [] == send_request_json_response(request) - - listdict[1] = {} - request = array.build_get_dictionary_item_empty_request() - assert listdict == send_request_json_response(request) - -def test_array_get_invalid(send_request_json_response): - request = array.build_get_invalid_request() - with pytest.raises(DecodeError): - send_request_json_response(request) - -def test_array_get_boolean_invalid_null(send_request_json_response): - request = array.build_get_boolean_invalid_null_request() - assert send_request_json_response(request), [True, None == False] - -def test_array_get_boolean_invalid_string(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_boolean_invalid_string_request() - assert send_request_json_response(request) == [True, "boolean", False] - -def test_array_get_int_invalid_null(send_request_json_response): - request = array.build_get_int_invalid_null_request() - assert send_request_json_response(request), [1, None == 0] - -def test_array_get_int_invalid_string(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_int_invalid_string_request() - assert send_request_json_response(request) == [1, "integer", 0] - -def test_array_get_long_invalid_null(send_request_json_response): - request = array.build_get_long_invalid_null_request() - assert send_request_json_response(request), [1, None == 0] - -def test_array_get_long_invalid_string(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_long_invalid_string_request() - assert send_request_json_response(request) == [1, "integer", 0] - -def test_array_get_float_invalid_null(send_request_json_response): - request = array.build_get_float_invalid_null_request() - assert send_request_json_response(request), [0.0, None == -1.2e20] - -def test_array_get_float_invalid_string(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_float_invalid_string_request() - assert send_request_json_response(request) == [1, "number", 0] - -def test_array_get_double_invalid_null(send_request_json_response): - request = array.build_get_double_invalid_null_request() - assert send_request_json_response(request), [0.0, None == -1.2e20] - -def test_array_get_double_invalid_string(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_double_invalid_string_request() - assert send_request_json_response(request) == [1, "number", 0] - -def test_array_get_string_with_invalid(send_request_json_response): - request = array.build_get_string_with_invalid_request() - assert send_request_json_response(request), ["foo", "123" == "foo2"] - -def test_array_get_date_invalid_null(send_request_json_response): - request = array.build_get_date_invalid_null_request() - assert send_request_json_response(request), [isodate.parse_date("2012-01-01"), None == isodate.parse_date("1776-07-04")] - -def test_array_get_date_invalid_chars(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_date_invalid_chars_request() - assert send_request_json_response(request) == ["2011-03-22", "date"] - -def test_array_get_date_time_invalid_null(send_request_json_response): - request = array.build_get_date_time_invalid_null_request() - assert send_request_json_response(request), [isodate.parse_datetime("2000-12-01T00:00:01Z") == None] - -def test_array_get_date_time_invalid_chars(send_request_json_response): - # don't raise deserialization error bc we're not msrest deserializing - request = array.build_get_date_time_invalid_chars_request() - assert send_request_json_response(request) == ['2000-12-01t00:00:01z', 'date-time'] - -def test_array_get_base64_url(send_request_json_response, deserializer): - test_array = ['a string that gets encoded with base64url'.encode(), - 'test string'.encode(), - 'Lorem ipsum'.encode()] - request = array.build_get_base64_url_request() - response = send_request_json_response(request) - assert [deserializer.deserialize_base64(s) for s in send_request_json_response(request)] == test_array - -def test_array_enum_valid(send_request, send_request_json_response): - request = array.build_get_enum_valid_request() - response = send_request_json_response(request) - assert response == ['foo1', 'foo2', 'foo3'] - request = array.build_put_enum_valid_request(json=response) - send_request(request) - -def test_array_string_enum_valid(send_request, send_request_json_response): - request = array.build_get_string_enum_valid_request() - response = send_request_json_response(request) - assert response == ['foo1', 'foo2', 'foo3'] - request = array.build_put_string_enum_valid_request(json=response) - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_binary.py b/test/vanilla/low-level/AcceptanceTests/test_binary.py deleted file mode 100644 index 4d0e6c9318e..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_binary.py +++ /dev/null @@ -1,48 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -import json -from bodybinarylowlevel import BinaryWithContentTypeApplicationJson -from bodybinarylowlevel.rest import upload - -@pytest.fixture -def client(): - with BinaryWithContentTypeApplicationJson() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -def test_upload_file(send_request): - request = upload.build_file_request(content=json.dumps({"more": "cowbell"}), headers={"Content-Type": "application/json"}) - send_request(request) - -def test_upload_binary(send_request): - request = upload.build_binary_request(content=b"Hello, world!", headers={"Content-Type": "application/octet-stream"}) - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_bool.py b/test/vanilla/low-level/AcceptanceTests/test_bool.py deleted file mode 100644 index 7f3a6fd1d40..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_bool.py +++ /dev/null @@ -1,71 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from bodybooleanlowlevel import AutoRestBoolTestService -from bodybooleanlowlevel.rest import bool -import pytest -from azure.core.exceptions import DecodeError - -@pytest.fixture -def client(): - with AutoRestBoolTestService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_model_get_true(send_request_json_response): - request = bool.build_get_true_request() - assert send_request_json_response(request) == True - -def test_model_get_false(send_request_json_response): - request = bool.build_get_false_request() - assert not send_request_json_response(request) - -def test_model_get_null(send_request): - request = bool.build_get_null_request() - assert send_request(request).text() == '' - -def test_model_put_false(send_request): - request = bool.build_put_false_request() - send_request(request) - -def test_model_put_true(send_request): - request = bool.build_put_true_request() - send_request(request) - -def test_model_get_invalid(send_request): - request = bool.build_get_invalid_request() - with pytest.raises(DecodeError): - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_byte.py b/test/vanilla/low-level/AcceptanceTests/test_byte.py deleted file mode 100644 index 1d502bb42f1..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_byte.py +++ /dev/null @@ -1,65 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from bodybytelowlevel import AutoRestSwaggerBATByteService -from bodybytelowlevel.rest import byte -from base64 import b64encode, b64decode -import pytest - -@pytest.fixture -def client(): - with AutoRestSwaggerBATByteService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -def test_non_ascii(send_request): - def deserialize_base64(attr): - padding = '=' * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace('-', '+').replace('_', '/') - return b64decode(encoded) - tests = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x0FB, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) - request = byte.build_put_non_ascii_request(json=b64encode(tests).decode()) - send_request(request) - - request = byte.build_get_non_ascii_request() - assert tests == deserialize_base64(send_request(request).text()) - -def test_get_null(send_request): - request = byte.build_get_null_request() - assert send_request(request).text() == '' - -def test_get_empty(send_request): - request = byte.build_get_empty_request() - assert b'""' == send_request(request).content # in convenience layer, we deserialize as bytearray specif - -def test_get_invalid(send_request): - request = byte.build_get_invalid_request() - assert send_request(request).content == b'"::::SWAGGER::::"' diff --git a/test/vanilla/low-level/AcceptanceTests/test_complex.py b/test/vanilla/low-level/AcceptanceTests/test_complex.py deleted file mode 100644 index 3fd9094b7d5..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_complex.py +++ /dev/null @@ -1,619 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import pytest -import isodate -from datetime import datetime, timedelta, tzinfo -from bodycomplexlowlevel import AutoRestComplexTestService -from bodycomplexlowlevel.rest import ( - basic, - primitive, - readonlyproperty, - array, - dictionary, - polymorphism, - polymorphicrecursive, - inheritance, -) -from azure.core.exceptions import HttpResponseError -from bodycomplexlowlevel._serialization import Serializer, Deserializer -from base64 import b64decode, b64encode - -class UTC(tzinfo): - def utcoffset(self,dt): - return timedelta(hours=0,minutes=0) - - def tzname(self,dt): - return "Z" - - def dst(self,dt): - return timedelta(0) - -import pytest - -@pytest.fixture -def client(): - with AutoRestComplexTestService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -@pytest.fixture -def min_date(): - min_date = datetime.min - return min_date.replace(tzinfo=UTC()) - -def test_basic_get_and_put_valid(send_request, send_request_json_response): - # GET basic/valid - request = basic.build_get_valid_request() - basic_result = send_request_json_response(request) - assert 2 == basic_result['id'] - assert "abc" == basic_result['name'] - assert "YELLOW" == basic_result['color'] - - # PUT basic/valid - json = { - "id": 2, - "name": "abc", - "color": "Magenta", - } - request = basic.build_put_valid_request(json=json) - send_request(request) - json = { - "id": 2, - "name": "abc", - "color": "Magenta", - } - request = basic.build_put_valid_request(json=json) - send_request(request) - -def test_basic_get_empty(send_request, send_request_json_response): - # GET basic/empty - request = basic.build_get_empty_request() - basic_result = send_request_json_response(request) - assert basic_result == {} - -def test_basic_get_null(send_request_json_response): - # GET basic/null - request = basic.build_get_null_request() - basic_result = send_request_json_response(request) - assert basic_result['id'] is None - assert basic_result['name'] is None - -def test_basic_get_not_provided(send_request): - # GET basic/notprovided - request = basic.build_get_not_provided_request() - assert send_request(request).text() == '' - -def test_basic_get_invalid(send_request_json_response): - # GET basic/invalid - request = basic.build_get_invalid_request() - basic_result = send_request_json_response(request) - # it's deserialized as invalid bc the id is not a number - # with LLC, we don't care thought - assert basic_result['id'] == 'a' - assert basic_result['name'] == 'abc' - -# COMPLEX TYPE WITH PRIMITIVE PROPERTIES -def test_primitive_get_and_put_int(send_request, send_request_json_response): - # GET primitive/integer - request = primitive.build_get_int_request() - int_result = send_request_json_response(request) - assert -1 == int_result['field1'] - assert 2 == int_result['field2'] - - # PUT primitive/integer - int_request = {'field1':-1, 'field2':2} - request = primitive.build_put_int_request(json=int_request) - send_request(request) - -def test_primitive_get_and_put_long(send_request, send_request_json_response): - # GET primitive/long - request = primitive.build_get_long_request() - long_result = send_request_json_response(request) - assert 1099511627775 == long_result['field1'] - assert -999511627788 == long_result['field2'] - - # PUT primitive/long - json = {'field1':1099511627775, 'field2':-999511627788} - request = primitive.build_put_long_request(json=json) - send_request(request) - -def test_primitive_get_and_put_float(send_request, send_request_json_response): - # GET primitive/float - request = primitive.build_get_float_request() - float_result = send_request_json_response(request) - assert 1.05 == float_result['field1'] - assert -0.003 == float_result['field2'] - - # PUT primitive/float - json = { - "field1": 1.05, - "field2": -0.003 - } - request = primitive.build_put_float_request(json=json) - send_request(request) - -def test_primitive_get_and_put_double(send_request, send_request_json_response): - # GET primitive/double - request = primitive.build_get_double_request() - double_result =send_request_json_response(request) - 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 - json = { - "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 - } - request = primitive.build_put_double_request(json=json) - send_request(request) - -def test_primitive_get_and_put_bool(send_request, send_request_json_response): - # GET primitive/bool - request = primitive.build_get_bool_request() - bool_result = send_request_json_response(request) - assert bool_result['field_true'] - assert not bool_result['field_false'] - - # PUT primitive/bool - json = { - "field_true": True, - "field_false": False - } - request = primitive.build_put_bool_request(json=json) - send_request(request) - -def test_primitive_get_and_put_string(send_request, send_request_json_response): - # GET primitive/string - request = primitive.build_get_string_request() - string_result = send_request_json_response(request) - assert "goodrequest" == string_result['field'] - assert "" == string_result['empty'] - assert string_result['null'] is None - - # PUT primitive/string - json = { - "null": None, - "empty": "", - "field": "goodrequest" - } - request = primitive.build_put_string_request(json=json) - send_request(request) - -def test_primitive_get_and_put_date(send_request, send_request_json_response): - # GET primitive/date - request = primitive.build_get_date_request() - date_result = send_request_json_response(request) - 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']) - - json = { - "field": '0001-01-01', - "leap": '2016-02-29' - } - request = primitive.build_put_date_request(json=json) - send_request(request) - -def test_primitive_get_and_put_date_time(send_request, send_request_json_response, min_date): - # GET primitive/datetime - request = primitive.build_get_date_time_request() - datetime_result = send_request_json_response(request) - - assert min_date == Deserializer.deserialize_iso(datetime_result['field']) - - json = { - "field": "0001-01-01T00:00:00Z", - "now": "2015-05-18T18:38:00Z" - } - request = primitive.build_put_date_time_request(json=json) - send_request(request) - -def test_primitive_get_and_put_date_time_rfc1123(send_request, send_request_json_response): - # GET primitive/datetimerfc1123 - request = primitive.build_get_date_time_rfc1123_request() - datetimerfc1123_result = send_request_json_response(request) - - # 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']) - - # we can still model year 1 though with the latest msrest update - json = { - "field": Serializer.serialize_rfc(isodate.parse_datetime("0001-01-01T00:00:00Z")), - "now": Serializer.serialize_rfc(isodate.parse_datetime("2015-05-18T11:38:00Z")) - } - request = primitive.build_put_date_time_rfc1123_request(json=json) - send_request(request) - -def test_primitive_get_and_put_duration(send_request, send_request_json_response): - # GET primitive/duration - expected = timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11) - request = primitive.build_get_duration_request() - duration_result = send_request_json_response(request) - assert expected == Deserializer.deserialize_duration(duration_result['field']) - - request = primitive.build_put_duration_request(json={"field": Serializer.serialize_duration(expected)}) - send_request(request) - -def test_primitive_get_and_put_byte(send_request, send_request_json_response): - # GET primitive/byte - request = primitive.build_get_byte_request() - byte_result = send_request_json_response(request) - valid_bytes = bytearray([0x0FF, 0x0FE, 0x0FD, 0x0FC, 0x000, 0x0FA, 0x0F9, 0x0F8, 0x0F7, 0x0F6]) - assert valid_bytes == bytearray(b64decode(byte_result['field'])) - - # PUT primitive/byte - request = primitive.build_put_byte_request(json={"field": b64encode(valid_bytes).decode()}) - send_request(request) - -# COMPLEX TYPE WITH READ ONLY PROPERTIES - -def test_readonlyproperty_get_and_put_valid(send_request, send_request_json_response): - # GET readonly/valid - valid_obj = {"size": 2, 'id': '1234'} - request = readonlyproperty.build_get_valid_request() - readonly_result = send_request_json_response(request) - assert readonly_result == valid_obj - - # PUT readonly/valid - request = readonlyproperty.build_put_valid_request(json=2) - assert send_request(request).text() == '' - -# COMPLEX TYPE WITH ARRAY PROPERTIES - -def test_array_get_and_put_valid(send_request, send_request_json_response): - # GET array/valid - request = array.build_get_valid_request() - array_result = send_request_json_response(request) - 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 - - # PUT array/valid - request = array.build_put_valid_request(json={"array": array_value}) - send_request(request) - -def test_array_get_and_put_empty(send_request, send_request_json_response): - - # GET array/empty - request = array.build_get_empty_request() - array_result = send_request_json_response(request) - assert 0 == len(array_result['array']) - - # PUT array/empty - request = array.build_put_empty_request(json={"array": []}) - send_request(request) - -def test_array_get_not_provided(send_request_json_response): - # Get array/notprovided - request = array.build_get_not_provided_request() - assert send_request_json_response(request) == {} - -# COMPLEX TYPE WITH DICTIONARY PROPERTIES - -def test_dictionary_get_and_put_valid(send_request, send_request_json_response): - # GET dictionary/valid - request = dictionary.build_get_valid_request() - dict_result = send_request_json_response(request) - assert 5 == len(dict_result['defaultProgram']) - - dict_val = {'txt':'notepad', 'bmp':'mspaint', 'xls':'excel', 'exe':'', '':None} - assert dict_val == dict_result['defaultProgram'] - - # PUT dictionary/valid - request = dictionary.build_put_valid_request(json={"defaultProgram": dict_val}) - send_request(request) - -def test_dictionary_get_and_put_empty(send_request, send_request_json_response): - # GET dictionary/empty - request = dictionary.build_get_empty_request() - dict_result = send_request_json_response(request) - assert 0 == len(dict_result['defaultProgram']) - - # PUT dictionary/empty - request = dictionary.build_put_empty_request(json={"defaultProgram": {}}) - send_request(request) - -def test_dictionary_get_and_null(send_request_json_response): - # GET dictionary/null - request = dictionary.build_get_null_request() - dictionary_result = send_request_json_response(request) - assert dictionary_result['defaultProgram'] is None - -def test_dictionary_get_not_provided(send_request_json_response): - # GET dictionary/notprovided - request = dictionary.build_get_not_provided_request() - assert send_request_json_response(request) == {} - - -# COMPLEX TYPES THAT INVOLVE INHERITANCE - -def test_inheritance_get_and_put_valid(send_request, send_request_json_response): - # GET inheritance/valid - request = inheritance.build_get_valid_request() - inheritance_result = send_request_json_response(request) - 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 - json = { - 'id': 2, - 'name': "Siameeee", - 'color': "green", - 'breed': "persian", - 'hates': [{"id": 1, "name": "Potato", "food": "tomato"}, - {"id": -1, "name": "Tomato", "food": "french fries"}] - } - request = inheritance.build_put_valid_request(json=json) - send_request(request) - -# COMPLEX TYPES THAT INVOLVE POLYMORPHISM - -def test_get_composed_with_discriminator(send_request_json_response): - request = polymorphism.build_get_composed_with_discriminator_request() - result = send_request_json_response(request) - assert result['sampleSalmon']['fish.type'] == "DotSalmon" - -def test_get_composed_without_discriminator(send_request_json_response): - request = polymorphism.build_get_composed_without_discriminator_request() - result = send_request_json_response(request) - with pytest.raises(KeyError): - result['sampleSalmon']['fish.type'] # shouldn't have a discriminator - -def test_polymorphism_get_and_put_valid(send_request, send_request_json_response): - # GET polymorphism/valid - request = polymorphism.build_get_valid_request() - result = send_request_json_response(request) - 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 - - - # PUT polymorphism/valid - json = { - "fishtype": "salmon", - "species": "king", - "length": 1.0, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20.0, - "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "age": 105, - "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - }, - { - "fishtype": "goblin", - "species": "scary", - "length": 30.0, - "age": 1, - "birthday": "2015-08-08T00:00:00.000Z", - "jawsize": 5, - "color": "pinkish-gray" - } - ], - "location": "alaska", - "iswild": True - } - request = polymorphism.build_put_valid_request(json=json) - send_request(request) - -def test_polymorphism_put_valid_missing_required(send_request): - json = { - "fishtype": "salmon", - "species": "king", - "length": 1.0, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20.0, - "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "age": 105, - "picture": "//////4=" - } - ], - "location": "alaska", - "iswild": True - } - - request = polymorphism.build_put_valid_missing_required_request(json=json) - - # in convenience layer, this raises a ValidationError (when generated with client side validation) - with pytest.raises(HttpResponseError) as e: - send_request(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(send_request, send_request_json_response): - # GET polymorphicrecursive/valid - # discriminator checks now just rely on checking the value of the discrimintaor - request = polymorphicrecursive.build_get_valid_request() - result = send_request_json_response(request) - 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" - - json = { - "fishtype": "salmon", - "species": "king", - "length": 1.0, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20.0, - "siblings": [ - { - "fishtype": "salmon", - "species": "coho", - "length": 2.0, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20.0, - "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "age": 105, - "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } - ], - "location": "atlantic", - "iswild": True - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "siblings": [], - "age": 105, - "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } - ], - "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "siblings": [], - "age": 105, - "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - } - ], - "location": "alaska", - "iswild": True - } - # PUT polymorphicrecursive/valid - request = polymorphicrecursive.build_put_valid_request(json=json) - send_request(request) - - -# Complex types that uses additional properties and polymorphism -def test_polymorphism_get_and_put_complicated(send_request, send_request_json_response): - request = polymorphism.build_get_complicated_request() - response = send_request_json_response(request) - request = polymorphism.build_put_complicated_request(json=response) - send_request(request) - -# Complex types that uses missing discriminator - -def test_polymorphism_get_and_put_missing_discriminator(send_request, send_request_json_response): - json = { - "fishtype": "salmon", - "species": "king", - "length": 1.0, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20.0, - "age": 6, - "birthday": "2012-01-05T01:00:00.000Z" - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10.0, - "age": 105, - "birthday": "1900-01-05T01:00:00.000Z", - "picture": "//////4=" - }, - { - "fishtype": "goblin", - "species": "scary", - "length": 30.0, - "age": 1, - "birthday": "2015-08-08T00:00:00.000Z", - "jawsize": 5, - "color": "pinkish-gray" - } - ], - "location": "alaska", - "iswild": True - } - # Not raise is enough of a test - request = polymorphism.build_put_missing_discriminator_request(json=json) - send_request(request) - - # Dot syntax - request = polymorphism.build_get_dot_syntax_request() - dot_salmon = send_request_json_response(request) - 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" diff --git a/test/vanilla/low-level/AcceptanceTests/test_config.py b/test/vanilla/low-level/AcceptanceTests/test_config.py deleted file mode 100644 index 7bdad777917..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_config.py +++ /dev/null @@ -1,42 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from azure.core.pipeline.policies import HttpLoggingPolicy -from bodystringlowlevel 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"} - ) - 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"}) diff --git a/test/vanilla/low-level/AcceptanceTests/test_constants.py b/test/vanilla/low-level/AcceptanceTests/test_constants.py deleted file mode 100644 index 7600b5b4513..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_constants.py +++ /dev/null @@ -1,57 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from constantslowlevel import AutoRestSwaggerConstantService -from constantslowlevel.rest import contants - -@pytest.fixture -def client(): - with AutoRestSwaggerConstantService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -def test_put_client_constants(client, send_request): - assert client._config.header_constant == True - assert client._config.query_constant == 100 - assert client._config.path_constant == "path" - - request = contants.build_put_client_constants_request() - send_request(request) - -def test_put_client_constants_override(): - 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" diff --git a/test/vanilla/low-level/AcceptanceTests/test_content_type.py b/test/vanilla/low-level/AcceptanceTests/test_content_type.py deleted file mode 100644 index e96d9af7bbb..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_content_type.py +++ /dev/null @@ -1,106 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import io -import sys -import pytest -from mediatypeslowlevel import MediaTypesClient -from mediatypeslowlevel.rest import * - -def test_json_body_no_content_type_kwarg(): - request = build_analyze_body_request(json={"source":"foo"}) - assert request.headers["Content-Type"] == "application/json" - assert request.content == '{"source": "foo"}' - - -def test_json_body_content_type_kwarg(): - request = build_analyze_body_request(json=[{"source":"foo"}], content_type="application/json+cloudevents-batch") - assert request.headers["Content-Type"] == "application/json+cloudevents-batch" - assert request.content == '[{"source": "foo"}]' - -def test_string_body_no_content_type_kwarg(): - request = build_analyze_body_request(content="hello") - assert request.headers["Content-Type"] == "text/plain" - -def test_string_body_content_type_kwarg(): - request = build_analyze_body_request(content="hello", content_type="text/plain") - assert request.headers["Content-Type"] == "text/plain" - -def test_io_body_no_content_type_kwarg(): - request = build_analyze_body_request(content=b"PDF") - assert not request.headers.get("Content-Type") - -def test_io_body_content_type_kwarg(): - request = build_analyze_body_request(content=b"PDF", content_type="application/pdf") - assert request.headers["Content-Type"] == "application/pdf" - -def test_stream_no_content_type_kwarg(): - test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') - with io.BytesIO(test_bytes) as stream_data: - request = build_analyze_body_request(content=stream_data) - assert not request.headers.get("Content-Type") - -def test_stream_content_type_kwarg(): - test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') - with io.BytesIO(test_bytes) as stream_data: - request = build_analyze_body_request(content=stream_data, content_type="application/json") - assert request.headers["Content-Type"] == "application/json" - -def test_file_description_no_content_type_kwarg(): - with open(__file__) as fd: - request = build_analyze_body_request(content=fd) - assert not request.headers.get("Content-Type") - -def test_file_description_content_type_kwarg(): - with open(__file__) as fd: - request = build_analyze_body_request(content=fd, content_type="application/pdf") - assert request.headers["Content-Type"] == "application/pdf" - -def test_content_type_in_headers_no_content_type_kwarg(): - request = build_analyze_body_request(content="", headers={"Content-Type": "application/exotic"}) - assert request.headers["Content-Type"] == "application/exotic" - -def test_content_type_in_headers_content_type_kwarg(): - request = build_analyze_body_request(content="", headers={"Content-Type": "application/exotic"}, content_type="application/pdf") - assert request.headers["Content-Type"] == "application/pdf" - -def test_stream_unread_until_send_request(): - class FakeStream: - def __init__(self): - self.call_count = 0 - - def streaming_body(self, data): - self.call_count += 1 - yield data - - fake_stream = FakeStream() - request = build_analyze_body_request(content=fake_stream.streaming_body(b"PDF")) - assert not request.headers.get("Content-Type") - assert fake_stream.call_count == 0 - MediaTypesClient().send_request(request) - assert fake_stream.call_count == 1 diff --git a/test/vanilla/low-level/AcceptanceTests/test_date.py b/test/vanilla/low-level/AcceptanceTests/test_date.py deleted file mode 100644 index 5d22c5bdf53..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_date.py +++ /dev/null @@ -1,86 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import isodate -import datetime - -from bodydatelowlevel import AutoRestDateTestService -from bodydatelowlevel.rest import date - -import pytest - -@pytest.fixture -def client(): - with AutoRestDateTestService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_model_get_and_put_max_date(send_request, send_request_json_response): - max_date = isodate.parse_date("9999-12-31T23:59:59.999999Z") - request = date.build_put_max_date_request(json=str(max_date)) - send_request(request) - - request = date.build_get_max_date_request() - assert max_date == isodate.parse_date(send_request_json_response(request)) - -def test_model_get_and_put_min_date(send_request, send_request_json_response): - min_date = isodate.parse_date("0001-01-01T00:00:00Z") - request = date.build_put_min_date_request(json=str(min_date)) - send_request(request) - - request = date.build_get_min_date_request() - assert min_date == isodate.parse_date(send_request_json_response(request)) - -def test_model_get_null(send_request): - request = date.build_get_null_request() - assert send_request(request).text() == '' - -def test_model_get_invalid_date(send_request_json_response): - request = date.build_get_invalid_date_request() - assert datetime.date(2001, 1, 1) == isodate.parse_date(send_request_json_response(request)) - -def test_model_get_overflow_date(send_request_json_response): - request = date.build_get_overflow_date_request() - with pytest.raises(ValueError) as ex: - isodate.parse_date(send_request_json_response(request)) - assert "day is out of range for month" in str(ex.value) - -def test_model_get_underflow_date(send_request_json_response): - request = date.build_get_underflow_date_request() - with pytest.raises(ValueError) as ex: - isodate.parse_date(send_request_json_response(request)) - assert "out of range" in str(ex.value) diff --git a/test/vanilla/low-level/AcceptanceTests/test_datetime.py b/test/vanilla/low-level/AcceptanceTests/test_datetime.py deleted file mode 100644 index 09c31adad66..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_datetime.py +++ /dev/null @@ -1,160 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import isodate - -from azure.core.exceptions import DeserializationError, SerializationError - -from bodydatetimelowlevel import AutoRestDateTimeTestService -from bodydatetimelowlevel.rest import datetime -from bodydatetimelowlevel._serialization import Serializer, Deserializer - -import pytest - -@pytest.fixture -def client(): - with AutoRestDateTimeTestService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -@pytest.fixture() -def serializer(): - return Serializer() - -@pytest.fixture() -def deserializer(): - return Deserializer() - -@pytest.fixture -def get_deserialized_iso(send_request_json_response, deserializer): - def _get_deserialized_iso(request): - return deserializer.deserialize_iso(send_request_json_response(request)) - return _get_deserialized_iso - -@pytest.fixture -def get_serialized_iso(serializer): - def _get_serialized_iso(date): - return serializer.serialize_iso(date) - return _get_serialized_iso - - -def test_utc_max_date_time(send_request, get_serialized_iso, get_deserialized_iso): - max_date = isodate.parse_datetime("9999-12-31T23:59:59.999Z") - request = datetime.build_get_utc_lowercase_max_date_time_request() - assert max_date == get_deserialized_iso(request) - - request = datetime.build_get_utc_uppercase_max_date_time_request() - assert get_deserialized_iso(request) == max_date - - request = datetime.build_put_utc_max_date_time_request(json=get_serialized_iso(max_date)) - send_request(request) - -def test_utc_max_date_time_7digits(send_request, get_serialized_iso, get_deserialized_iso): - max_date = isodate.parse_datetime("9999-12-31T23:59:59.999999Z") - request = datetime.build_get_utc_uppercase_max_date_time7_digits_request() - assert get_deserialized_iso(request) == max_date - - request = datetime.build_put_utc_max_date_time7_digits_request(json=get_serialized_iso(max_date)) - with pytest.raises(Exception): - # Python doesn't support 7 digits - send_request(request) - -def test_get_utc_min_date_time(send_request, get_serialized_iso, get_deserialized_iso): - min_date = isodate.parse_datetime("0001-01-01T00:00:00Z") - request = datetime.build_get_utc_min_date_time_request() - assert get_deserialized_iso(request) == min_date - - request = datetime.build_put_utc_min_date_time_request(json=get_serialized_iso(min_date)) - send_request(request) - -def test_get_local_negative_offset_min_date_time(send_request, send_request_json_response, get_serialized_iso): - request = datetime.build_get_local_negative_offset_min_date_time_request() - assert '0001-01-01T00:00:00-14:00' == send_request_json_response(request) - - request = datetime.build_put_local_negative_offset_min_date_time_request(json=get_serialized_iso(isodate.parse_datetime("0001-01-01T00:00:00-14:00"))) - send_request(request) - -def test_get_local_no_offset_min_date_time(get_deserialized_iso): - local_no_offset_min_date_time = isodate.parse_datetime("0001-01-01T00:00:00") - request = datetime.build_get_local_no_offset_min_date_time_request() - assert get_deserialized_iso(request) == local_no_offset_min_date_time - -def test_get_local_negative_offset_lowercase_max_date_time(send_request_json_response): - request = datetime.build_get_local_negative_offset_lowercase_max_date_time_request() - assert send_request_json_response(request) == "9999-12-31t23:59:59.999-14:00" - -def test_get_local_negative_offset_uppercase_max_date_time(send_request_json_response): - request = datetime.build_get_local_negative_offset_uppercase_max_date_time_request() - assert send_request_json_response(request) == "9999-12-31T23:59:59.999-14:00" - -def test_local_positive_offset_min_date_time(send_request_json_response, get_serialized_iso): - request = datetime.build_get_local_positive_offset_min_date_time_request() - assert send_request_json_response(request) == "0001-01-01T00:00:00+14:00" - - with pytest.raises(SerializationError): - datetime.build_get_local_positive_offset_min_date_time_request(json=get_serialized_iso(isodate.parse_datetime("0001-01-01T00:00:00+14:00"))) - - -def test_local_positive_offset_max_date_time(send_request_json_response, send_request, get_serialized_iso): - request = datetime.build_get_local_positive_offset_lowercase_max_date_time_request() - assert send_request_json_response(request) == "9999-12-31t23:59:59.999+14:00" - - request = datetime.build_get_local_positive_offset_uppercase_max_date_time_request() - assert send_request_json_response(request) == "9999-12-31T23:59:59.999+14:00" - - request = datetime.build_put_local_positive_offset_max_date_time_request(json=get_serialized_iso(isodate.parse_datetime("9999-12-31T23:59:59.999999+14:00"))) - send_request(request) - -def test_get_null(send_request, get_serialized_iso, get_deserialized_iso): - request = datetime.build_get_null_request() - assert send_request(request).text() == '' - -def test_get_overflow(send_request_json_response): - request = datetime.build_get_overflow_request() - assert send_request_json_response(request) == "9999-12-31T23:59:59.999-14:00" - -def test_get_invalid(send_request_json_response): - request = datetime.build_get_invalid_request() - assert send_request_json_response(request) == "201O-18-90D00:89:56.9AX" - -def test_get_underflow(send_request_json_response): - request = datetime.build_get_underflow_request() - assert send_request_json_response(request) == "0000-00-00T00:00:00.000+00:00" - -def test_put_local_negative_offset_max_date_time(get_serialized_iso): - with pytest.raises(SerializationError): - datetime.build_put_local_negative_offset_max_date_time_request(json=get_serialized_iso(isodate.parse_datetime("9999-12-31T23:59:59.999999-14:00"))) diff --git a/test/vanilla/low-level/AcceptanceTests/test_datetime_rfc.py b/test/vanilla/low-level/AcceptanceTests/test_datetime_rfc.py deleted file mode 100644 index 7ee1f707cf5..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_datetime_rfc.py +++ /dev/null @@ -1,91 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import isodate - - -from bodydatetimerfc1123lowlevel import AutoRestRFC1123DateTimeTestService -from bodydatetimerfc1123lowlevel.rest import datetimerfc1123 -from bodydatetimerfc1123lowlevel._serialization import Serializer - -import pytest - -@pytest.fixture -def client(): - with AutoRestRFC1123DateTimeTestService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -@pytest.fixture -def serializer(): - return Serializer() - - -def test_get_null(send_request): - request = datetimerfc1123.build_get_null_request() - assert send_request(request).text() == '' - -def test_get_invalid(send_request_json_response): - request = datetimerfc1123.build_get_invalid_request() - assert "Tue, 01 Dec 2000 00:00:0A ABC" == send_request_json_response(request) - -def test_get_underflow(send_request_json_response): - request = datetimerfc1123.build_get_underflow_request() - assert "Tue, 00 Jan 0000 00:00:00 GMT" == send_request_json_response(request) - -def test_get_overflow(send_request_json_response): - request = datetimerfc1123.build_get_overflow_request() - assert "Sat, 1 Jan 10000 00:00:00 GMT" == send_request_json_response(request) - -def test_utc_max_date_time(send_request, serializer): - max_date = isodate.parse_datetime("9999-12-31T23:59:59.999999Z") - - request = datetimerfc1123.build_get_utc_lowercase_max_date_time_request() - send_request(request) - - request = datetimerfc1123.build_get_utc_uppercase_max_date_time_request() - send_request(request) - - request = datetimerfc1123.build_put_utc_max_date_time_request(json=serializer.serialize_rfc(max_date)) - send_request(request) - -def test_utc_min_date_time(send_request, serializer): - min_date = isodate.parse_datetime("0001-01-01T00:00:00Z") - request = datetimerfc1123.build_get_utc_min_date_time_request() - send_request(request) - - request = datetimerfc1123.build_put_utc_min_date_time_request(json=serializer.serialize_rfc(min_date)) - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_dictionary.py b/test/vanilla/low-level/AcceptanceTests/test_dictionary.py deleted file mode 100644 index 61c73186630..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_dictionary.py +++ /dev/null @@ -1,391 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import isodate -import json -from datetime import timedelta -from bodydictionarylowlevel.rest import dictionary -from bodydictionarylowlevel import AutoRestSwaggerBATDictionaryService -from bodydictionarylowlevel._serialization import Serializer, Deserializer -from azure.core.exceptions import DecodeError -from .utils import JSON_DECODE_ERROR - -import pytest - -@pytest.fixture -def client(): - with AutoRestSwaggerBATDictionaryService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -@pytest.fixture -def get_deserialized_dict(send_request_json_response): - def _get_deserialized_dict(request, deserialize_value_callable): - json_response = send_request_json_response(request) - for key in json_response: - if json_response[key]: - json_response[key] = deserialize_value_callable(json_response[key]) - return json_response - return _get_deserialized_dict - -@pytest.fixture -def get_serialized_dict(): - def _get_serialized_dict(dict, serialize_value_callable): - return { - k: serialize_value_callable(v) for k, v in dict.items() - } - return _get_serialized_dict - - -@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} - -@pytest.fixture -def serializer(): - return Serializer() - -@pytest.fixture -def deserializer(): - return Deserializer() - -# Primitive types -def test_boolean_tfft(send_request, send_request_json_response): - tfft = {"0":True, "1":False, "2":False, "3":True} - request = dictionary.build_get_boolean_tfft_request() - assert tfft == send_request_json_response(request) - - request = dictionary.build_put_boolean_tfft_request(json=tfft) - send_request(request) - -def test_get_boolean_invalid(send_request_json_response): - invalid_null_dict = {"0":True, "1":None, "2":False} - request = dictionary.build_get_boolean_invalid_null_request() - assert invalid_null_dict == send_request_json_response(request) - - request = dictionary.build_get_boolean_invalid_string_request() - assert {"0": True, "1": "boolean", "2": False} == send_request_json_response(request) - -def test_integer_valid(send_request, send_request_json_response): - int_valid = {"0":1, "1":-1, "2":3, "3":300} - request = dictionary.build_get_integer_valid_request() - assert int_valid == send_request_json_response(request) - - request = dictionary.build_put_integer_valid_request(json=int_valid) - send_request(request) - -def test_get_int_invalid(send_request_json_response): - int_null_dict = {"0":1, "1":None, "2":0} - request = dictionary.build_get_int_invalid_null_request() - assert int_null_dict == send_request_json_response(request) - - request = dictionary.build_get_int_invalid_string_request() - assert {"0": 1, "1": "integer", "2": 0} == send_request_json_response(request) - -def test_long_valid(send_request, send_request_json_response): - long_valid = {"0":1, "1":-1, "2":3, "3":300} - request = dictionary.build_get_long_valid_request() - assert long_valid == send_request_json_response(request) - - request = dictionary.build_put_long_valid_request(json=long_valid) - send_request(request) - -def test_get_long_invalid(send_request_json_response): - long_null_dict = {"0":1, "1":None, "2":0} - request = dictionary.build_get_long_invalid_null_request() - assert long_null_dict == send_request_json_response(request) - - request = dictionary.build_get_long_invalid_string_request() - assert {"0": 1, "1": "integer", "2": 0} == send_request_json_response(request) - -def test_float_valid(send_request, send_request_json_response): - float_valid = {"0":0, "1":-0.01, "2":-1.2e20} - request = dictionary.build_get_float_valid_request() - assert float_valid == send_request_json_response(request) - - request = dictionary.build_put_float_valid_request(json=float_valid) - send_request(request) - -def test_get_float_invalid(send_request_json_response): - float_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - request = dictionary.build_get_float_invalid_null_request() - assert float_null_dict == send_request_json_response(request) - - request = dictionary.build_get_float_invalid_string_request() - assert {"0": 1, "1": "number", "2": 0} == send_request_json_response(request) - -def test_double_valid(send_request, send_request_json_response): - double_valid = {"0":0, "1":-0.01, "2":-1.2e20} - request = dictionary.build_get_double_valid_request() - assert double_valid == send_request_json_response(request) - - request = dictionary.build_put_double_valid_request(json=double_valid) - send_request(request) - -def test_get_double_invalid(send_request_json_response): - double_null_dict = {"0":0.0, "1":None, "2":-1.2e20} - request = dictionary.build_get_double_invalid_null_request() - assert double_null_dict == send_request_json_response(request) - - request = dictionary.build_get_double_invalid_string_request() - assert {"0": 1, "1": "number", "2": 0} == send_request_json_response(request) - -def test_string_valid(send_request, send_request_json_response): - string_valid = {"0":"foo1", "1":"foo2", "2":"foo3"} - request = dictionary.build_get_string_valid_request() - assert string_valid == send_request_json_response(request) - - request = dictionary.build_put_string_valid_request(json=string_valid) - send_request(request) - -def test_get_string_with_null_and_invalid(send_request_json_response): - string_null_dict = {"0":"foo", "1":None, "2":"foo2"} - string_invalid_dict = {"0":"foo", "1":123, "2":"foo2"} # in llc, we don't know we should serialize this whole thing as string, so serializes 123 as number - request = dictionary.build_get_string_with_null_request() - assert string_null_dict == send_request_json_response(request) - request = dictionary.build_get_string_with_invalid_request() - assert string_invalid_dict == send_request_json_response(request) - -def test_date_valid(send_request, get_serialized_dict, get_deserialized_dict, serializer, deserializer): - 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} - - request = dictionary.build_get_date_valid_request() - assert get_deserialized_dict(request, deserializer.deserialize_date) == valid_date_dict - - request = dictionary.build_put_date_valid_request(json=get_serialized_dict(valid_date_dict, serializer.serialize_date)) - send_request(request) - -def test_get_date_invalid(send_request_json_response, deserializer, get_deserialized_dict): - date_null_dict = {"0":isodate.parse_date("2012-01-01"), - "1":None, - "2":isodate.parse_date("1776-07-04")} - request = dictionary.build_get_date_invalid_null_request() - assert date_null_dict == get_deserialized_dict(request, deserializer.deserialize_date) - - request = dictionary.build_get_date_invalid_chars_request() - assert {"0": "2011-03-22", "1": "date"} == send_request_json_response(request) - -def test_date_time_valid(send_request, get_deserialized_dict, get_serialized_dict, serializer, deserializer): - 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} - - request = dictionary.build_get_date_time_valid_request() - assert valid_datetime_dict == get_deserialized_dict(request, deserializer.deserialize_iso) - - request = dictionary.build_put_date_time_valid_request( - json=get_serialized_dict(valid_datetime_dict, serializer.serialize_iso) - ) - send_request(request) - -def test_get_date_time_invalid(send_request_json_response, deserializer, get_deserialized_dict): - datetime_null_dict = {"0":isodate.parse_datetime("2000-12-01T00:00:01Z"), "1":None} - request = dictionary.build_get_date_time_invalid_null_request() - assert datetime_null_dict == get_deserialized_dict(request, deserializer.deserialize_iso) - - request = dictionary.build_get_date_time_invalid_chars_request() - assert {"0": "2000-12-01t00:00:01z", "1": "date-time"} == send_request_json_response(request) - -def test_date_time_rfc1123_valid(send_request, get_deserialized_dict, get_serialized_dict, serializer, deserializer): - 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} - - request = dictionary.build_get_date_time_rfc1123_valid_request() - assert valid_rfc_dict == get_deserialized_dict(request, deserializer.deserialize_rfc) - - request = dictionary.build_put_date_time_rfc1123_valid_request(json=get_serialized_dict(valid_rfc_dict, serializer.serialize_rfc)) - send_request(request) - -def test_get_duration_valid(send_request, serializer, deserializer, get_deserialized_dict, get_serialized_dict): - 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} - - request = dictionary.build_get_duration_valid_request() - assert valid_duration_dict == get_deserialized_dict(request, deserializer.deserialize_duration) - - request = dictionary.build_put_duration_valid_request(json=get_serialized_dict(valid_duration_dict, serializer.serialize_duration)) - send_request(request) - -def test_bytes_valid(send_request, serializer, deserializer, get_serialized_dict, get_deserialized_dict): - 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} - request = dictionary.build_put_byte_valid_request(json=get_serialized_dict(bytes_valid, serializer.serialize_bytearray)) - send_request(request) - - request = dictionary.build_get_byte_valid_request() - assert bytes_valid == get_deserialized_dict(request, deserializer.deserialize_bytearray) - -def test_get_byte_invalid_null(deserializer, get_deserialized_dict): - bytes4 = bytearray([0x0AB, 0x0AC, 0x0AD]) - bytes_null = {"0":bytes4, "1":None} - request = dictionary.build_get_byte_invalid_null_request() - assert bytes_null == get_deserialized_dict(request, deserializer.deserialize_bytearray) -def test_get_base64_url(deserializer, get_deserialized_dict): - test_dict = {'0': 'a string that gets encoded with base64url'.encode(), - '1': 'test string'.encode(), - '2': 'Lorem ipsum'.encode()} - request = dictionary.build_get_base64_url_request() - assert test_dict == get_deserialized_dict(request, deserializer.deserialize_base64) - -# Basic dictionary parsing -def test_empty(send_request, send_request_json_response): - - request = dictionary.build_get_empty_request() - assert {} == send_request_json_response(request) - - request = dictionary.build_put_empty_request(json={}) - send_request(request) - -def test_get_null_and_invalid(send_request, send_request_json_response): - - request = dictionary.build_get_null_request() - assert send_request(request).text() == '' - - request = dictionary.build_get_invalid_request() - with pytest.raises(DecodeError): - send_request_json_response(request) - -def test_get_null_key_and_value(send_request, send_request_json_response): - # {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. - request = dictionary.build_get_null_key_request() - with pytest.raises(DecodeError): - send_request_json_response(request) - - request = dictionary.build_get_null_value_request() - assert {"key1":None} == send_request_json_response(request) - -def test_get_empty_string_key(send_request_json_response): - request = dictionary.build_get_empty_string_key_request() - assert {"":"val1"} == send_request_json_response(request) - -def test_complex_valid(send_request, send_request_json_response, test_dict): - - request = dictionary.build_put_complex_valid_request(json=test_dict) - send_request(request) - - request = dictionary.build_get_complex_valid_request() - assert test_dict == send_request_json_response(request) - -def test_array_valid(send_request, send_request_json_response): - list_dict = {"0":["1","2","3"], "1":["4","5","6"], "2":["7","8","9"]} - - request = dictionary.build_put_array_valid_request(json=list_dict) - send_request(request) - - request = dictionary.build_get_array_valid_request() - assert list_dict == send_request_json_response(request) - -def test_dictionary_valid(send_request, send_request_json_response): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{"4":"four","5":"five","6":"six"}, - "2":{"7":"seven","8":"eight","9":"nine"}} - - request = dictionary.build_put_dictionary_valid_request(json=dict_dict) - send_request(request) - - request = dictionary.build_get_dictionary_valid_request() - assert dict_dict == send_request_json_response(request) - -def test_get_complex_null_and_empty(send_request, send_request_json_response): - - request = dictionary.build_get_complex_null_request() - assert send_request(request).text() == '' - - request = dictionary.build_get_complex_empty_request() - assert {} == send_request_json_response(request) - -def test_get_complex_item_null_and_empty(send_request_json_response, test_dict): - test_dict_null = {"0":test_dict["0"], "1":None, "2":test_dict["2"]} - - request = dictionary.build_get_complex_item_null_request() - assert test_dict_null == send_request_json_response(request) - - test_dict_empty = {"0":test_dict["0"], "1": {}, "2":test_dict["2"]} - - request = dictionary.build_get_complex_item_empty_request() - assert send_request_json_response(request) == test_dict_empty - -def test_get_array_empty(send_request, send_request_json_response): - request = dictionary.build_get_array_null_request() - assert send_request(request).text() == '' - - request = dictionary.build_get_array_empty_request() - assert {} == send_request_json_response(request) - -def test_get_array_item_null_and_empty(send_request_json_response): - list_dict = {"0":["1","2","3"], "1":None, "2":["7","8","9"]} - request = dictionary.build_get_array_item_null_request() - assert list_dict == send_request_json_response(request) - - # in convenience layer, we deserialize as {[str]}. Since we don't have that in llc, the value for "1" will be None, not an empty list - request = dictionary.build_get_array_item_empty_request() - list_dict = {"0":["1","2","3"], "1":[], "2":["7","8","9"]} - assert list_dict == send_request_json_response(request) - -def test_get_dictionary_null_and_empty(send_request, send_request_json_response): - request = dictionary.build_get_dictionary_null_request() - assert send_request(request).text() == '' - - request = dictionary.build_get_dictionary_empty_request() - assert {} == send_request_json_response(request) - -def test_get_dictionary_item_null_and_empty(send_request, send_request_json_response): - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":None, - "2":{"7":"seven","8":"eight","9":"nine"}} - request = dictionary.build_get_dictionary_item_null_request() - assert dict_dict == send_request_json_response(request) - - dict_dict = {"0":{"1":"one","2":"two","3":"three"}, - "1":{}, - "2":{"7":"seven","8":"eight","9":"nine"}} - request = dictionary.build_get_dictionary_item_empty_request() - assert dict_dict == send_request_json_response(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_duration.py b/test/vanilla/low-level/AcceptanceTests/test_duration.py deleted file mode 100644 index 0e01d4c4601..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_duration.py +++ /dev/null @@ -1,66 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from datetime import timedelta -import isodate -from azure.core.exceptions import DeserializationError - -from bodydurationlowlevel import AutoRestDurationTestService -from bodydurationlowlevel.rest import duration - -import pytest - -@pytest.fixture -def client(): - with AutoRestDurationTestService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_get_null_and_invalid(send_request, send_request_json_response): - request = duration.build_get_null_request() - assert send_request(request).text() == '' - - request = duration.build_get_invalid_request() - with pytest.raises(isodate.ISO8601Error): - isodate.parse_duration(send_request_json_response(request)) - -def test_positive_duration(send_request, send_request_json_response): - request = duration.build_get_positive_duration_request() - assert isodate.Duration(4, 45005, 0, years=3, months=6) == isodate.parse_duration(send_request_json_response(request)) - - request = duration.build_put_positive_duration_request(json=isodate.duration_isoformat(timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11))) - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_error_with_secrets.py b/test/vanilla/low-level/AcceptanceTests/test_error_with_secrets.py deleted file mode 100644 index 6e45f6fa0ad..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_error_with_secrets.py +++ /dev/null @@ -1,56 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from errorwithsecretslowlevel import ErrorWithSecrets, rest -from azure.core.exceptions import HttpResponseError - -@pytest.fixture -def client(): - with ErrorWithSecrets() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -def test_create_secret(send_request): - request = rest.build_create_secret_request( - headers={"authorization": "SharedKey 1c88a67921784300a462b2cb61da2339"}, - params={"key": "1c88a67921784300a462b2cb61da2339"}, - json={ "key": "1c88a67921784300a462b2cb61da2339" }, - ) - send_request(request) - -def test_raise_error_with_secrets(send_request): - request = rest.build_get_error_with_secrets_request() - with pytest.raises(HttpResponseError) as ex: - send_request(request) - # The actual test shouldn't have the secrets in the str output - # Until we figure out what to do for Python, just asserting - # what the string currently is for now. - assert "The user 'user@contoso.com' is unauthorized" in str(ex.value) diff --git a/test/vanilla/low-level/AcceptanceTests/test_extensible_enums.py b/test/vanilla/low-level/AcceptanceTests/test_extensible_enums.py deleted file mode 100644 index 00f0c5fed13..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_extensible_enums.py +++ /dev/null @@ -1,73 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from extensibleenumsswaggerlowlevel import PetStoreInc -from extensibleenumsswaggerlowlevel.rest import pet - -import pytest - -@pytest.fixture -def client(): - with PetStoreInc() as client: - yield client - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_get_by_pet_id(send_request_json_response): - # Now enum return are always string (Autorest.Python 3.0) - - request = pet.build_get_by_pet_id_request(pet_id="tommy") - tommy = send_request_json_response(request) - assert tommy["DaysOfWeek"] == "Monday" - assert tommy["IntEnum"] == "1" - - request = pet.build_get_by_pet_id_request(pet_id="casper") - casper = send_request_json_response(request) - assert casper["DaysOfWeek"] == "Weekend" - assert casper["IntEnum"] == "2" - - request = pet.build_get_by_pet_id_request(pet_id="scooby") - scooby = send_request_json_response(request) - 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" - -def test_add_pet(send_request_json_response): - retriever = { - "name": "Retriever", - "IntEnum": "3", - "DaysOfWeek": "Friday" - } - request = pet.build_add_pet_request(json=retriever) - returned_pet = send_request_json_response(request) - assert returned_pet["DaysOfWeek"] == "Friday" - assert returned_pet["IntEnum"] == "3" - assert returned_pet["name"] == "Retriever" diff --git a/test/vanilla/low-level/AcceptanceTests/test_file.py b/test/vanilla/low-level/AcceptanceTests/test_file.py deleted file mode 100644 index 2b189a82395..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_file.py +++ /dev/null @@ -1,91 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import io -from os.path import dirname, pardir, join, realpath -from bodyfilelowlevel import AutoRestSwaggerBATFileService -from bodyfilelowlevel.rest import files - -import pytest - -cwd = dirname(realpath(__file__)) - - -@pytest.fixture -def client(connection_data_block_size): - with AutoRestSwaggerBATFileService( - connection_data_block_size=connection_data_block_size) as client: - yield client - -@pytest.mark.parametrize('connection_data_block_size', [1000]) -def test_get_file(client): - file_length = 0 - with io.BytesIO() as file_handle: - request = files.build_get_file_request() - with client.send_request(request, stream=True) as response: - assert not response._internal_response._content_consumed - assert not response.is_closed - assert not response.is_stream_consumed - for data in response.iter_raw(): - # assert 0 < len(data) <= stream.block_size - file_length += len(data) - file_handle.write(data) - - assert file_length != 0 - assert response.is_closed - assert response.is_stream_consumed - assert response._internal_response._content_consumed - 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: - sample_data = hash(data.read()) - assert sample_data == hash(file_handle.getvalue()) - -@pytest.mark.parametrize('connection_data_block_size', [4096]) -def test_get_empty_file(client): - file_length = 0 - with io.BytesIO() as file_handle: - request = files.build_get_empty_file_request() - with client.send_request(request, stream=True) as response: - assert not response._internal_response._content_consumed - - for data in response.iter_raw(): - file_length += len(data) - file_handle.write(data) - - assert file_length == 0 - -@pytest.mark.parametrize('connection_data_block_size', [4096]) -def test_files_long_running(client): - file_length = 0 - request = files.build_get_file_large_request() - with client.send_request(request, stream=True) as response: - for data in response.iter_bytes(): - assert 0 < len(data) <= response.block_size - file_length += len(data) - - assert file_length == 3000 * 1024 * 1024 diff --git a/test/vanilla/low-level/AcceptanceTests/test_form_data.py b/test/vanilla/low-level/AcceptanceTests/test_form_data.py deleted file mode 100644 index db7713ef544..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_form_data.py +++ /dev/null @@ -1,153 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import subprocess -import sys -import io -import os -import tempfile -from os.path import dirname, pardir, join, realpath - -cwd = dirname(realpath(__file__)) -log_level = int(os.environ.get('PythonLogLevel', 30)) - -tests = realpath(join(cwd, pardir, "Expected", "AcceptanceTests")) -sys.path.append(join(tests, "BodyFormData")) - - -from bodyformdatalowlevel import AutoRestSwaggerBATFormDataService -from bodyformdatalowlevel.rest import formdata -import pytest - -@pytest.fixture -def dummy_file(): - 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 - ) as client: - yield client - -@pytest.mark.skip("Not generating formdata bodies anymore.") -def test_file_upload_stream(client): - - test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') - result = io.BytesIO() - with io.BytesIO(test_bytes) as stream_data: - files = { - "fileContent": stream_data, - "fileName": "UploadFile.txt", - } - request = formdata.build_upload_file_request(files=files) - with client.send_request(request, stream=True) as response: - response.raise_for_status() - for data in response.iter_bytes(): - result.write(data) - assert result.getvalue().decode() == test_string - -@pytest.mark.skip("Not generating formdata bodies anymore.") -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 = { - "fileContent": upload_data, - "fileName": name, - } - request = formdata.build_upload_file_request(files=files) - with client.send_request(request, stream=True) as response: - response.raise_for_status() - for data in response.iter_bytes(): - result.write(data) - 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') - - result = io.BytesIO() - with io.BytesIO(test_bytes) as stream_data: - request = formdata.build_upload_file_via_body_request(content=stream_data, headers={"Content-Type": "application/octet-stream"}) - with client.send_request(request, stream=True) as response: - response.raise_for_status() - for data in response.iter_bytes(): - result.write(data) - assert result.getvalue().decode() == test_string - - result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: - request = formdata.build_upload_file_via_body_request(content=upload_data, headers={"Content-Type": "application/octet-stream"}) - with client.send_request(request, stream=True) as response: - response.raise_for_status() - for data in response.iter_bytes(): - result.write(data) - 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') - - 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))) - if not block: - break - yield block - - result = io.BytesIO() - with io.BytesIO(test_bytes) as stream_data: - streamed_upload = stream_upload(stream_data, len(test_string), 2) - request = formdata.build_upload_file_via_body_request(content=streamed_upload, headers={"Content-Type": "application/octet-stream"}) - with client.send_request(request, stream=True) as response: - response.raise_for_status() - for data in response.iter_bytes(): - result.write(data) - assert result.getvalue().decode() == test_string - - result = io.BytesIO() - with open(dummy_file, 'rb') as upload_data: - streamed_upload = stream_upload(upload_data, len("Test file"), 2) - request = formdata.build_upload_file_via_body_request(content=streamed_upload, headers={"Content-Type": "application/octet-stream"}) - with client.send_request(request, stream=True) as response: - response.raise_for_status() - for data in response.iter_bytes(): - result.write(data) - assert result.getvalue().decode() == "Test file" \ No newline at end of file diff --git a/test/vanilla/low-level/AcceptanceTests/test_header.py b/test/vanilla/low-level/AcceptanceTests/test_header.py deleted file mode 100644 index c0578bd69e5..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_header.py +++ /dev/null @@ -1,230 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import isodate -from datetime import datetime, timedelta -from base64 import b64decode - -from headerlowlevel import AutoRestSwaggerBATHeaderService -from headerlowlevel.rest import header - -import pytest - -@pytest.fixture -def client(): - with AutoRestSwaggerBATHeaderService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_value_response_header(client, base_send_request): - def _send_request(request): - return base_send_request(client, request).headers['value'] - return _send_request - -# NOTE: in llc, we don't know to deserialize response headers as int / datetime etc. So you'll see they'll just be strings, not ints etc -def test_integer(send_request, send_request_value_response_header): - - request = header.build_param_integer_request(scenario="positive", value=1) - send_request(request) - request = header.build_param_integer_request(scenario="negative", value=-2) - send_request(request) - - request = header.build_response_integer_request(scenario="positive") - assert send_request_value_response_header(request) == "1" - - request = header.build_response_integer_request(scenario="negative") - assert send_request_value_response_header(request) == "-2" - -def test_long(send_request, send_request_value_response_header): - request = header.build_param_long_request(scenario="positive", value=105) - send_request(request) - request = header.build_param_long_request(scenario="negative", value=-2) - send_request(request) - - request = header.build_response_long_request(scenario="positive") - assert send_request_value_response_header(request) == "105" - - request = header.build_response_long_request(scenario="negative") - assert send_request_value_response_header(request) == "-2" - -def test_float(send_request, send_request_value_response_header): - request = header.build_param_float_request(scenario="positive", value=0.07) - send_request(request) - - request = header.build_param_float_request(scenario="negative", value=-3.0) - send_request(request) - - request = header.build_response_float_request(scenario="positive") - assert abs(0.07 - float(send_request_value_response_header(request))) < 0.00001 - - request = header.build_response_float_request(scenario="negative") - assert abs(-3.0 - float(send_request_value_response_header(request))) < 0.00001 - -def test_double(send_request, send_request_value_response_header): - request = header.build_param_double_request(scenario="positive", value=7e120) - send_request(request) - - request = header.build_param_double_request(scenario="negative", value=-3.0) - send_request(request) - - request = header.build_response_double_request(scenario="positive") - assert send_request_value_response_header(request) == "7e+120" - - request = header.build_response_double_request(scenario="negative") - assert send_request_value_response_header(request) == "-3" - -def test_bool(send_request, send_request_value_response_header): - request = header.build_param_bool_request(scenario="true", value=True) - send_request(request) - request = header.build_param_bool_request(scenario="false", value=False) - send_request(request) - - request = header.build_response_bool_request(scenario="true") - assert send_request_value_response_header(request) == 'true' - - request = header.build_response_bool_request(scenario="false") - assert send_request_value_response_header(request) == 'false' - -def test_string(send_request, send_request_value_response_header): - request = header.build_param_string_request(scenario="valid", value="The quick brown fox jumps over the lazy dog") - send_request(request) - - request = header.build_param_string_request(scenario="null", value=None) - send_request(request) - - request = header.build_param_string_request(scenario="empty", value="") - send_request(request) - - request = header.build_response_string_request(scenario="valid") - assert send_request_value_response_header(request) == "The quick brown fox jumps over the lazy dog" - - request = header.build_response_string_request(scenario="null") - assert send_request_value_response_header(request) == "null" # TODO This should be None - - request = header.build_response_string_request(scenario="empty") - assert send_request_value_response_header(request) == "" - -def test_enum(send_request, send_request_value_response_header): - request = header.build_param_enum_request(scenario="valid", value="GREY") - send_request(request) - - request = header.build_param_enum_request(scenario="valid", value="GREY") - send_request(request) - - request = header.build_param_enum_request(scenario="null", value=None) - send_request(request) - - - request = header.build_response_enum_request(scenario="valid") - assert send_request_value_response_header(request) == "GREY" - - # We receive an empty string. - # Starting msrest 0.4.22, we consider that if a string is not in the enum, this not - # a Deserialization issue and we return the string. - # Here we now return empty string without failin **on purpose** - # with pytest.raises(DeserializationError): - request = header.build_response_enum_request(scenario="null") - assert send_request_value_response_header(request) == "" - -def test_date(send_request, send_request_value_response_header): - request = header.build_param_date_request(scenario="valid", value=isodate.parse_date("2010-01-01")) - send_request(request) - request = header.build_param_date_request(scenario="min", value=datetime.min) - send_request(request) - - request = header.build_response_date_request(scenario="valid") - assert send_request_value_response_header(request) == str(isodate.parse_date("2010-01-01")) - - request = header.build_response_date_request(scenario="min") - assert send_request_value_response_header(request) == str(isodate.parse_date("0001-01-01")) - -def test_datetime(send_request, send_request_value_response_header): - request = header.build_param_datetime_request(scenario="valid", value=isodate.parse_datetime("2010-01-01T12:34:56Z")) - send_request(request) - request = header.build_param_datetime_request(scenario="min", value=datetime.min) - send_request(request) - - request = header.build_response_datetime_request(scenario="valid") - assert send_request_value_response_header(request) == '2010-01-01T12:34:56Z' - - request = header.build_response_datetime_request(scenario="min") - assert send_request_value_response_header(request) == '0001-01-01T00:00:00Z' - -def test_datetime_rfc(send_request, send_request_value_response_header): - request = header.build_param_datetime_rfc1123_request(scenario="valid", value=isodate.parse_datetime("2010-01-01T12:34:56Z")) - send_request(request) - - request = header.build_param_datetime_rfc1123_request(scenario="min", value=datetime.min) - send_request(request) - - request = header.build_response_datetime_rfc1123_request(scenario="valid") - assert send_request_value_response_header(request) == "Fri, 01 Jan 2010 12:34:56 GMT" - - # 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 - request = header.build_response_datetime_rfc1123_request(scenario="min") - assert send_request_value_response_header(request) == "Mon, 01 Jan 0001 00:00:00 GMT" - -def test_duration(send_request, send_request_value_response_header): - request = header.build_param_duration_request(scenario="valid", value=timedelta(days=123, hours=22, minutes=14, seconds=12, milliseconds=11)) - send_request(request) - - request = header.build_response_duration_request(scenario="valid") - assert send_request_value_response_header(request) == 'P123DT22H14M12.011S' # raw str of the above timedelta - -def test_byte(send_request, send_request_value_response_header): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') - request = header.build_param_byte_request(scenario="valid", value=u_bytes) - send_request(request) - - request = header.build_response_byte_request(scenario="valid") - assert bytearray(b64decode(send_request_value_response_header(request))) == u_bytes - -def test_response_existing_key(send_request): - - request = header.build_param_existing_key_request(user_agent_parameter="overwrite") - send_request(request) - request = header.build_response_existing_key_request() - assert send_request(request).headers['User-Agent'] == "overwrite" - -def test_response_protected_key(send_request): - # This test is only valid for C#, which content-type can't be override this way - #client.header.param_protected_key("text/html") - - # This test has different result compare to C#, which content-type is saved in another place. - request = header.build_response_protected_key_request() - assert send_request(request).headers['Content-Type'] == "text/html; charset=utf-8" - -def test_custom_request_id(send_request): - custom_headers = {"x-ms-client-request-id": "9C4D50EE-2D56-4CD3-8152-34347DC9F2B0"} - request = header.build_custom_request_id_request(headers=custom_headers) - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_hooks.py b/test/vanilla/low-level/AcceptanceTests/test_hooks.py deleted file mode 100644 index fdb092672d2..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_hooks.py +++ /dev/null @@ -1,54 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from azure.core.pipeline.policies import CustomHookPolicy -from bodyarraylowlevel import AutoRestSwaggerBATArrayService -from bodyarraylowlevel.rest import array - -def is_rest(obj): - return hasattr(obj, "content") - -def test_raw_request_hook_send_request(): - def _callback(request): - assert 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.send_request(array.build_get_array_empty_request()) - assert "I entered the callback!" in str(ex.value) - -def test_raw_response_hook_send_request(): - def _callback(response): - assert 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: - client.send_request(array.build_get_array_empty_request()) - assert "I entered the callback!" in str(ex.value) diff --git a/test/vanilla/low-level/AcceptanceTests/test_http.py b/test/vanilla/low-level/AcceptanceTests/test_http.py deleted file mode 100644 index b06921de6d0..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_http.py +++ /dev/null @@ -1,496 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import requests - -from azure.core.exceptions import HttpResponseError -from azure.core.pipeline.policies import ContentDecodePolicy, RetryPolicy, HeadersPolicy, RedirectPolicy - -from httpinfrastructurelowlevel import AutoRestHttpInfrastructureTestService -from httpinfrastructurelowlevel.rest import ( - http_client_failure, - http_failure, - http_redirects, - http_retry, - http_server_failure, - http_success, - multiple_responses, -) - -import pytest - - -@pytest.fixture() -def client(cookie_policy): - """Create a AutoRestHttpInfrastructureTestService client with test server credentials.""" - policies = [ - HeadersPolicy(), - ContentDecodePolicy(), - RedirectPolicy(), - RetryPolicy(), - cookie_policy - ] - with AutoRestHttpInfrastructureTestService(policies=policies) as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -@pytest.fixture -def send_request_assert_status(client, base_send_request): - def _send_request(request, status_code): - response = base_send_request(client, request) - assert response.status_code == status_code - return _send_request - -@pytest.fixture -def send_request_assert_raises_with_message(client, base_send_request): - def _send_request(request, message): - with pytest.raises(HttpResponseError) as ex: - base_send_request(client, request) - assert ex.value.message == message - return _send_request - -@pytest.fixture -def send_request_assert_raises_with_status(client, base_send_request): - def _send_request(request, status_code): - with pytest.raises(HttpResponseError) as ex: - base_send_request(client, request) - assert ex.value.status_code == status_code - return _send_request - -@pytest.fixture -def send_request_assert_raises_with_status_and_message(client, base_send_request): - def _send_request(request, status_code, message): - with pytest.raises(HttpResponseError) as ex: - base_send_request(client, request) - assert ex.value.status_code == status_code - assert ex.value.message == message - assert message in str(ex.value) - return _send_request - -@pytest.fixture -def send_request_assert_raises_with_status_and_response_contains_message(client, base_send_request): - def _send_request(request, status_code, message): - with pytest.raises(HttpResponseError) as ex: - base_send_request(client, request) - assert ex.value.status_code == status_code - assert ex.value.response.json()['message'] == message - return _send_request - -def test_get200_model204(send_request, send_request_assert_status, send_request_assert_raises_with_status_and_response_contains_message): - # a lot of these tests raised in high level bc we made some 200 status codes errors in high level - # can't do this in low level, so these don't actually raise - request = multiple_responses.build_get200_model204_no_model_default_error200_valid_request() - send_request_assert_status(request, 200) - - request = multiple_responses.build_get200_model204_no_model_default_error201_invalid_request() - send_request_assert_status(request, 201) - - request = multiple_responses.build_get200_model204_no_model_default_error202_none_request() - send_request_assert_status(request, 202) - - request = multiple_responses.build_get200_model204_no_model_default_error204_valid_request() - - assert send_request(request).text() == '' - - request = multiple_responses.build_get200_model204_no_model_default_error400_valid_request() - send_request_assert_raises_with_status_and_response_contains_message(request, 400, "client error") - -def test_get200_model201(send_request_json_response, send_request_assert_status, send_request_assert_raises_with_status_and_response_contains_message): - request = multiple_responses.build_get200_model201_model_default_error200_valid_request() - send_request_assert_status(request, 200) - - request = multiple_responses.build_get200_model201_model_default_error201_valid_request() - b_model = send_request_json_response(request) - assert b_model is not None - assert b_model['statusCode'] == "201" - assert b_model['textStatusCode'] == "Created" - - request = multiple_responses.build_get200_model201_model_default_error400_valid_request() - send_request_assert_raises_with_status_and_response_contains_message(request, 400, "client error") - -def test_get200_model_a201_model_c404(send_request_json_response, send_request_assert_raises_with_status_and_response_contains_message, send_request_assert_raises_with_status): - request = multiple_responses.build_get200_model_a201_model_c404_model_d_default_error200_valid_request() - a_model = send_request_json_response(request) - assert a_model['statusCode']== "200" - - request = multiple_responses.build_get200_model_a201_model_c404_model_d_default_error201_valid_request() - - c_model = send_request_json_response(request) - assert c_model['httpCode'] == "201" - - request = multiple_responses.build_get200_model_a201_model_c404_model_d_default_error404_valid_request() - send_request_assert_raises_with_status(request, 404) # in high level, this doesn't raise and returns a model since we've made 404 a valid status code. can't do that in llc - - request = multiple_responses.build_get200_model_a201_model_c404_model_d_default_error400_valid_request() - send_request_assert_raises_with_status_and_response_contains_message(request, 400, "client error") - -def test_get202_none204(send_request, send_request_assert_raises_with_status, send_request_assert_raises_with_status_and_response_contains_message): - request = multiple_responses.build_get202_none204_none_default_error202_none_request() - send_request(request) - - request = multiple_responses.build_get202_none204_none_default_error204_none_request() - send_request(request) - - request = multiple_responses.build_get202_none204_none_default_error400_valid_request() - send_request_assert_raises_with_status_and_response_contains_message(request, 400, "client error") - - request = multiple_responses.build_get202_none204_none_default_none202_invalid_request() - send_request(request) - - request = multiple_responses.build_get202_none204_none_default_none204_none_request() - send_request(request) - - request = multiple_responses.build_get202_none204_none_default_none400_none_request() - send_request_assert_raises_with_status(request, 400) - - request = multiple_responses.build_get202_none204_none_default_none400_invalid_request() - send_request_assert_raises_with_status(request, 400) - -def test_get_default_model_a200(send_request, send_request_assert_status): - request = multiple_responses.build_get_default_model_a200_valid_request() - send_request_assert_status(request, 200) - - request = multiple_responses.build_get_default_model_a200_none_request() - assert send_request(request).text() == '' - - request = multiple_responses.build_get_default_model_a200_valid_request() - send_request(request) - request = multiple_responses.build_get_default_model_a200_none_request() - send_request(request) - -def test_get_default_none200(send_request): - request = multiple_responses.build_get_default_none200_invalid_request() - send_request(request) - - requst = multiple_responses.build_get_default_none200_none_request() - send_request(request) - -def test_get_default_none400(send_request_assert_raises_with_status): - request = multiple_responses.build_get_default_none400_invalid_request() - send_request_assert_raises_with_status(request, 400) - - request = multiple_responses.build_get_default_none400_none_request() - send_request_assert_raises_with_status(request, 400) - -def test_get200_model_a200(send_request, send_request_assert_status): - request = multiple_responses.build_get200_model_a200_none_request() - assert send_request(request).text() == '' - - request = multiple_responses.build_get200_model_a200_valid_request() - send_request_assert_status(request, 200) - - request = multiple_responses.build_get200_model_a200_invalid_request() - send_request_assert_status(request, 200) # in high level it's supposed to deserialize as exception model "MyException", can't do that in LLC - -def test_get200_model_a400(send_request_assert_raises_with_status): - request = multiple_responses.build_get200_model_a400_none_request() - send_request_assert_raises_with_status(request, 400) - - request = multiple_responses.build_get200_model_a400_valid_request() - send_request_assert_raises_with_status(request, 400) - - request = multiple_responses.build_get200_model_a400_invalid_request() - send_request_assert_raises_with_status(request, 400) - -def test_get200_model_a202(send_request_assert_status): - request = multiple_responses.build_get200_model_a202_valid_request() - send_request_assert_status(request, 202) # raises in HLC bc we've marked all status codes that are not "200" as errors - -def test_server_error_status_codes_501(send_request_assert_raises_with_status): - request = http_server_failure.build_head501_request() - send_request_assert_raises_with_status(request, requests.codes.not_implemented) - - request = http_server_failure.build_get501_request() - send_request_assert_raises_with_status(request, requests.codes.not_implemented) - -def test_server_error_status_codes_505(send_request_assert_raises_with_status): - request = http_server_failure.build_post505_request() - send_request_assert_raises_with_status(request, requests.codes.http_version_not_supported) - - request = http_server_failure.build_delete505_request() - send_request_assert_raises_with_status(request, requests.codes.http_version_not_supported) - -def test_retry_status_codes_408(send_request): - request = http_retry.build_head408_request() - send_request(request) - -def test_retry_status_codes_502(send_request): - request = http_retry.build_get502_request() - send_request(request) - - request = http_retry.build_options502_request() - send_request(request) - -def test_retry_status_codes_500(send_request): - request = http_retry.build_put500_request() - send_request(request) - request = http_retry.build_patch500_request() - send_request(request) - -def test_retry_status_codes_503(send_request): - request = http_retry.build_post503_request() - send_request(request) - - request = http_retry.build_delete503_request() - send_request(request) - -def test_retry_status_codes_504(send_request): - request = http_retry.build_put504_request() - send_request(request) - - request = http_retry.build_patch504_request() - send_request(request) - -def test_error_status_codes_400(send_request_assert_raises_with_status): - request = http_client_failure.build_head400_request() - send_request_assert_raises_with_status(request, requests.codes.bad_request) - - request = http_client_failure.build_get400_request() - send_request_assert_raises_with_status(request, requests.codes.bad_request) - - # TODO, 4042586: Support options operations in swagger modeler - #self.assert_raises_with_status(requests.codes.bad_request, - # client.http_client_failure.options400) - - request = http_client_failure.build_put400_request() - send_request_assert_raises_with_status(request, requests.codes.bad_request) - - request = http_client_failure.build_patch400_request() - send_request_assert_raises_with_status(request, requests.codes.bad_request) - - request = http_client_failure.build_post400_request() - send_request_assert_raises_with_status(request, requests.codes.bad_request) - - request = http_client_failure.build_delete400_request() - send_request_assert_raises_with_status(request, requests.codes.bad_request) - -def test_error_status_codes_401(send_request_assert_raises_with_status): - request = http_client_failure.build_head401_request() - send_request_assert_raises_with_status(request, requests.codes.unauthorized) - -def test_error_status_codes_402(send_request_assert_raises_with_status): - request = http_client_failure.build_get402_request() - send_request_assert_raises_with_status(request, requests.codes.payment_required) - -def test_error_status_codes_403(send_request_assert_raises_with_status): - # TODO, 4042586: Support options operations in swagger modeler - #self.assert_raises_with_status(requests.codes.forbidden, - # client.http_client_failure.options403) - - request = http_client_failure.build_get403_request() - send_request_assert_raises_with_status(request, requests.codes.forbidden) - -def test_error_status_codes_404(send_request_assert_raises_with_status): - request = http_client_failure.build_put404_request() - send_request_assert_raises_with_status(request, requests.codes.not_found) - -def test_error_status_codes_405(send_request_assert_raises_with_status): - request = http_client_failure.build_patch405_request() - send_request_assert_raises_with_status(request, requests.codes.method_not_allowed) - -def test_error_status_codes_406(send_request_assert_raises_with_status): - request = http_client_failure.build_post406_request() - send_request_assert_raises_with_status(request, requests.codes.not_acceptable) - -def test_error_status_codes_407(send_request_assert_raises_with_status): - request = http_client_failure.build_delete407_request() - send_request_assert_raises_with_status(request, requests.codes.proxy_authentication_required) - -def test_error_status_codes_409(send_request_assert_raises_with_status): - request = http_client_failure.build_put409_request() - send_request_assert_raises_with_status(request, requests.codes.conflict) - -def test_error_status_codes_410(send_request_assert_raises_with_status): - request = http_client_failure.build_head410_request() - send_request_assert_raises_with_status(request, requests.codes.gone) - -def test_error_status_codes_411(send_request_assert_raises_with_status): - - request = http_client_failure.build_get411_request() - send_request_assert_raises_with_status(request, requests.codes.length_required) - - # TODO, 4042586: Support options operations in swagger modeler - #self.assert_raises_with_status(requests.codes.precondition_failed, - # client.http_client_failure.options412) - - request = http_client_failure.build_get412_request() - send_request_assert_raises_with_status(request, requests.codes.precondition_failed) - - request = http_client_failure.build_put413_request() - send_request_assert_raises_with_status(request, requests.codes.request_entity_too_large) - - request = http_client_failure.build_patch414_request() - send_request_assert_raises_with_status(request, requests.codes.request_uri_too_large) - - request = http_client_failure.build_post415_request() - send_request_assert_raises_with_status(request, requests.codes.unsupported_media) - - request = http_client_failure.build_get416_request() - send_request_assert_raises_with_status(request, requests.codes.requested_range_not_satisfiable) - - request = http_client_failure.build_delete417_request() - send_request_assert_raises_with_status(request, requests.codes.expectation_failed) - - request = http_client_failure.build_head429_request() - send_request_assert_raises_with_status(request, 429) - -def test_redirect_to_300(send_request_assert_status): - request = http_redirects.build_get300_request() - send_request_assert_status(request, 200) - request = http_redirects.build_head300_request() - send_request_assert_status(request, 200) - -def test_redirect_to_301(send_request_assert_status): - request = http_redirects.build_head301_request() - send_request_assert_status(request, 200) - - - request = http_redirects.build_get301_request() - send_request_assert_status(request, 200) - - request = http_redirects.build_put301_request() - send_request_assert_status(request, requests.codes.moved_permanently) - -def test_redirect_to_302(send_request_assert_status): - request = http_redirects.build_head302_request() - send_request_assert_status(request, 200) - - request = http_redirects.build_get302_request() - send_request_assert_status(request, 200) - - request = http_redirects.build_patch302_request() - send_request_assert_status(request, requests.codes.found) - -def test_redicret_to_303(send_request_assert_status): - request = http_redirects.build_post303_request() - send_request_assert_status(request, 200) - -def test_redirect_to_307(send_request_assert_status): - request = http_redirects.build_head307_request() - send_request_assert_status(request, 200) - - request = http_redirects.build_get307_request() - send_request_assert_status(request, 200) - - request = http_redirects.build_options307_request() - send_request_assert_status(request, 200) - - request = http_redirects.build_put307_request() - send_request_assert_status(request, 200) - - request = http_redirects.build_post307_request() - send_request_assert_status(request, 200) - - request = http_redirects.build_patch307_request() - send_request_assert_status(request, 200) - - request = http_redirects.build_delete307_request() - send_request_assert_status(request, 200) - -def test_bad_request_status_assert(send_request_assert_raises_with_message): - request = http_failure.build_get_empty_error_request() - send_request_assert_raises_with_message(request, "Operation returned an invalid status 'Bad Request'") - -def test_no_error_model_status_assert(send_request_assert_raises_with_status_and_response_contains_message): - request = http_failure.build_get_no_model_error_request() - send_request_assert_raises_with_status_and_response_contains_message(request, requests.codes.bad_request, "NoErrorModel") - -def test_success_status_codes_200(send_request): - request = http_success.build_head200_request() - send_request(request) - request = http_success.build_get200_request() - assert send_request(request).text() - - request = http_success.build_put200_request() - send_request(request) - - request = http_success.build_post200_request() - send_request(request) - - request = http_success.build_patch200_request() - send_request(request) - - request = http_success.build_delete200_request() - send_request(request) - - # TODO, 4042586: Support options operations in swagger modeler - #assert client.http_success.options200() - -def test_success_status_codes_201(send_request): - request = http_success.build_put201_request() - send_request(request) - - request = http_success.build_post201_request() - send_request(request) - -def test_success_status_codes_202(send_request): - request = http_success.build_put202_request() - send_request(request) - - request = http_success.build_post202_request() - send_request(request) - - request = http_success.build_patch202_request() - send_request(request) - - request = http_success.build_delete202_request() - send_request(request) - -def test_success_status_codes_204(send_request): - request = http_success.build_head204_request() - send_request(request) - - request = http_success.build_put204_request() - send_request(request) - - request = http_success.build_post204_request() - send_request(request) - - request = http_success.build_delete204_request() - send_request(request) - - request = http_success.build_patch204_request() - send_request(request) - -def test_success_status_codes_404(send_request_assert_raises_with_status): - # raises bc in high level we're able to mark 404 as a valid status code, but can't do that in llc - request = http_success.build_head404_request() - send_request_assert_raises_with_status(request, 404) - -def test_empty_no_content(send_request_assert_raises_with_status): - request = http_failure.build_get_no_model_empty_request() - send_request_assert_raises_with_status(request, requests.codes.bad_request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_inputs.py b/test/vanilla/low-level/AcceptanceTests/test_inputs.py deleted file mode 100644 index cf6f130583d..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_inputs.py +++ /dev/null @@ -1,79 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from bodycomplexlowlevel.rest import basic -try: - from urlparse import urlparse # type: ignore -except ImportError: - from urllib.parse import urlparse - -def test_header_input(): - request = basic.build_get_empty_request(headers={"hello": "world!"}) - assert len(request.headers) == 2 - assert request.headers["Accept"] == "application/json" - assert request.headers["hello"] == "world!" - -def test_header_input_override(): - request = basic.build_get_empty_request(headers={"Accept": "my/content-type"}) - assert request.headers == {"Accept": "my/content-type"} - -def test_header_none_input(): - # just check we can build a request with empty headers - basic.build_get_empty_request(headers=None) - -def test_header_case_insensitive(): - accept_keys = ["accept", "Accept", "ACCEPT", "aCCePT"] - for accept_key in accept_keys: - request = basic.build_get_empty_request(headers={accept_key: "my/content-type"}) - assert request.headers == {"Accept": "my/content-type"} - -def test_header_kwarg_and_header(): - request = basic.build_put_valid_request(json=None, headers={"content-type": "shouldn't/be-me"}, content_type="my/json") - assert len(request.headers) == 2 - assert request.headers["content-type"] == "my/json" - assert request.headers["accept"] == "application/json" - -def test_query_input(): - request = basic.build_get_empty_request(params={"foo": "bar"}) - assert urlparse(request.url).query == "foo=bar" - -def test_query_input_override(): - request = basic.build_put_valid_request(params={"api-version": "2021-10-01"}) - - assert urlparse(request.url).query == "api-version=2021-10-01" - -def test_query_none_input(): - # just check we can build a request with empty params - basic.build_get_empty_request(params=None) - -def test_query_case_insensitive(): - query_keys = ["foo", "Foo", "FOO", "fOo"] - for query_key in query_keys: - request = basic.build_get_empty_request(params={query_key: "bar"}) - assert urlparse(request.url).query.lower() == "foo=bar" - -def test_query_kwarg_and_header(): - request = basic.build_put_valid_request(params={"api-version": "shouldn't-be-me"}, api_version="2021-10-01") - assert urlparse(request.url).query == "api-version=2021-10-01" diff --git a/test/vanilla/low-level/AcceptanceTests/test_integer.py b/test/vanilla/low-level/AcceptanceTests/test_integer.py deleted file mode 100644 index 5ed0d1bdd26..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_integer.py +++ /dev/null @@ -1,119 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import datetime -from bodyintegerlowlevel import AutoRestIntegerTestService -from bodyintegerlowlevel.rest import int as int_rest -from azure.core.exceptions import DecodeError -import pytest -import calendar - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - 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 - -@pytest.fixture -def client(): - with AutoRestIntegerTestService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -def test_max_min_32_bit(send_request): - request = int_rest.build_put_max32_request(json=2147483647) # sys.maxint - send_request(request) - - request = int_rest.build_put_min32_request(json=-2147483648) - send_request(request) - -def test_max_min_64_bit(send_request): - request = int_rest.build_put_max64_request(json=9223372036854776000) # sys.maxsize - send_request(request) - - request = int_rest.build_put_min64_request(json=-9223372036854776000) - send_request(request) - -def test_get_null_and_invalid(send_request): - request = int_rest.build_get_null_request() - send_request(request) - - request = int_rest.build_get_invalid_request() - with pytest.raises(DecodeError): - send_request(request) - -def test_get_overflow(send_request): - # Testserver excepts these to fail, but they won't in Python and it's ok. - - request = int_rest.build_get_overflow_int32_request() - send_request(request) - - request = int_rest.build_get_overflow_int64_request() - send_request(request) - -def test_get_underflow(send_request): - request = int_rest.build_get_underflow_int32_request() - send_request(request) - - request = int_rest.build_get_underflow_int64_request() - send_request(request) - -def test_unix_time_date(send_request): - unix_date = datetime.datetime(year=2016, month=4, day=13) - - input = calendar.timegm(unix_date.utctimetuple()) - request = int_rest.build_put_unix_time_date_request(json=int(input)) - send_request(request) - - request = int_rest.build_get_unix_time_request() - assert unix_date.utctimetuple() == datetime.datetime.fromtimestamp(send_request(request).json(), TZ_UTC).utctimetuple() - -def test_get_null_and_invalid_unix_time(send_request): - request = int_rest.build_get_null_unix_time_request() - assert send_request(request).text() == '' - - request = int_rest.build_get_invalid_unix_time_request() - with pytest.raises(DecodeError): - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_media_types.py b/test/vanilla/low-level/AcceptanceTests/test_media_types.py deleted file mode 100644 index 0a65745e3f7..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_media_types.py +++ /dev/null @@ -1,100 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from mediatypeslowlevel import MediaTypesClient -from mediatypeslowlevel.rest import * -import json -import pytest - -@pytest.fixture -def client(): - with MediaTypesClient() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_pdf(send_request_json_response): - request = build_analyze_body_request(content=b"PDF", content_type="application/pdf") - assert send_request_json_response(request) == "Nice job with PDF" - -def test_json(send_request_json_response): - request = build_analyze_body_request(json={"source":"foo"}) - assert send_request_json_response(request) == "Nice job with JSON" - -def test_content_type_with_encoding(send_request_json_response): - request = build_content_type_with_encoding_request(content="hello", content_type='text/plain; charset=UTF-8') - assert send_request_json_response(request) == "Nice job sending content type with encoding" - -def test_pdf_no_accept_header(send_request): - request = build_analyze_body_no_accept_header_request(content=b"PDF", content_type="application/pdf") - send_request(request) - -def test_json_no_accept_header(send_request): - request = build_analyze_body_no_accept_header_request(json={"source":"foo"}) - send_request(request) - -def test_binary_body_two_content_types(send_request): - json_input = json.dumps({"hello":"world"}) - request = build_binary_body_with_two_content_types_request(content=json_input, content_type="application/json") - send_request(request) - - content = b"hello, world" - request = build_binary_body_with_two_content_types_request(content=content, content_type="application/octet-stream") - send_request(request) - -def test_binary_body_three_content_types(send_request): - json_input = json.dumps({"hello":"world"}) - request = build_binary_body_with_three_content_types_request(content=json_input, content_type="application/json") - send_request(request) - - content = b"hello, world" - request = build_binary_body_with_three_content_types_request(content=content, content_type="application/octet-stream") - send_request(request) - - content = "hello, world" - request = build_binary_body_with_three_content_types_request(content=content, content_type="text/plain") - send_request(request) - -def test_body_three_types(send_request): - request = build_body_three_types_request(json={"hello":"world"}) - send_request(request) - - content = b"hello, world" - request = build_body_three_types_request(content=content, content_type="application/octet-stream") - send_request(request) - - content = "hello, world" - request = build_body_three_types_request(content=content, content_type="text/plain") - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_merge_patch_json.py b/test/vanilla/low-level/AcceptanceTests/test_merge_patch_json.py deleted file mode 100644 index 988ed6ad981..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_merge_patch_json.py +++ /dev/null @@ -1,44 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from mergepatchjsonlowlevel import rest, MergePatchJsonClient - -import pytest - -@pytest.fixture -def client(): - with MergePatchJsonClient() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -def test_merge_patch_json(send_request): - request = rest.build_patch_single_request(json={"foo": "bar"}, content_type="application/merge-patch+json") - assert request.headers["Content-Length"] == "14" - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_model_flattening.py b/test/vanilla/low-level/AcceptanceTests/test_model_flattening.py deleted file mode 100644 index 6905b718eb4..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_model_flattening.py +++ /dev/null @@ -1,293 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import sys -from modelflatteninglowlevel import AutoRestResourceFlatteningTestService, rest - -import pytest - -@pytest.fixture() -def client(): - with AutoRestResourceFlatteningTestService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - - -def test_flattening_array(send_request, send_request_json_response): - #Array - request = rest.build_get_array_request() - result = send_request_json_response(request) - 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"] - # Resource 2 - 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'] - - json = [ - { - 'tags': { - 'tag1': 'value1', - 'tag2': 'value3' - }, - 'location': 'West US' - }, - { - 'location': 'Building 44' - } - ] - request = rest.build_put_array_request(json=json) - send_request(request) - -def test_flattening_dictionary(send_request, send_request_json_response): - - request = rest.build_get_dictionary_request() - result = send_request_json_response(request) - 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"] - # Resource 2 - 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'] - - json = { - "Resource1": { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, - "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } - }, - "Resource2": { - "location": "Building 44", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } - } - - request = rest.build_put_dictionary_request(json=json) - send_request(request) - -def test_flattening_complex_object(send_request, send_request_json_response): - - #ResourceCollection - request = rest.build_get_resource_collection_request() - result = send_request_json_response(request) - - #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"] - # Resource 2 - 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'] - - #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"] - # Resource 2 - 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'] - - #productresource - assert "7" == result['productresource']['id'] - assert "Resource7" == result['productresource']['name'] - - json = { - "productresource": { - "location": "India", - "properties": { - "p.name": "Azure", - "type": "Flat" - } - }, - "arrayofresources": [ - { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, - "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } - }, - { - "location": "East US", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } - ], - "dictionaryofresources": { - "Resource1": { - "tags": { - "tag1": "value1", - "tag2": "value3" - }, - "location": "West US", - "properties": { - "p.name": "Product1", - "type": "Flat" - } - }, - "Resource2": { - "location": "Building 44", - "properties": { - "p.name": "Product2", - "type": "Flat" - } - } - } - } - request = rest.build_put_resource_collection_request(json=json) - send_request(request) - -def test_model_flattening_simple(send_request_json_response): - json = { - "base_product_id": "123", - "base_product_description": "product description", - "details": { - "max_product_display_name": "max name", - "max_product_capacity": "Large", - "max_product_image": { - "generic_value": "https://generic", - "@odata.value": "http://foo" - } - } - } - request = rest.build_put_simple_product_request(json=json) - result = send_request_json_response(request) - assert json == result - -def test_model_flattening_with_parameter_flattening(send_request_json_response): - - json = { - "base_product_id": "123", - "base_product_description": "product description", - "details": { - "max_product_display_name": "max name", - "max_product_capacity": "Large", - "max_product_image": { - "@odata.value": "http://foo" - } - } - } - - request = rest.build_post_flattened_simple_product_request(json=json) - result = send_request_json_response(request) - assert result == json - -def test_model_flattening_with_grouping(send_request_json_response): - json = { - "base_product_id": "123", - "base_product_description": "product description", - "details": { - "max_product_display_name": "max name", - "max_product_capacity": "Large", - "max_product_image": { - "@odata.value": "http://foo" - } - } - } - request = rest.build_put_simple_product_with_grouping_request( - name='groupproduct', - json=json - ) - result = send_request_json_response(request) - assert result == json diff --git a/test/vanilla/low-level/AcceptanceTests/test_multiple_inheritance.py b/test/vanilla/low-level/AcceptanceTests/test_multiple_inheritance.py deleted file mode 100644 index a5f14046e0b..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_multiple_inheritance.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from multipleinheritancelowlevel import MultipleInheritanceServiceClient -from multipleinheritancelowlevel.rest import * -import pytest - -@pytest.fixture -def client(): - with MultipleInheritanceServiceClient() as client: - yield client - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_get_pet(send_request_json_response): - request = build_get_pet_request() - assert {"name": "Peanut"} == send_request_json_response(request) - -def test_put_pet(send_request_json_response): - request = build_put_pet_request(json={"name": "Butter"}) - result = send_request_json_response(request) - assert result == "Pet was correct!" - -def test_get_horse(send_request_json_response): - request = build_get_horse_request() - assert {"name": "Fred", "isAShowHorse": True} == send_request_json_response(request) - -def test_put_horse(send_request_json_response): - request = build_put_horse_request(json={"name": "General", "isAShowHorse": False}) - result = send_request_json_response(request) - assert result == "Horse was correct!" - -def test_get_feline(send_request_json_response): - request = build_get_feline_request() - assert {"meows": True, "hisses": True} == send_request_json_response(request) - -def test_put_feline(send_request_json_response): - request = build_put_feline_request(json={"meows": False, "hisses": True}) - result = send_request_json_response(request) - assert result == "Feline was correct!" - -def test_get_cat(send_request_json_response): - request = build_get_cat_request() - assert {"name": "Whiskers", "likesMilk": True, "meows": True, "hisses": True} == send_request_json_response(request) - -def test_put_cat(send_request_json_response): - request = build_put_cat_request(json={"name": "Boots", "likesMilk": False, "meows": True, "hisses": False}) - assert send_request_json_response(request) == "Cat was correct!" - -def test_get_kitten(send_request_json_response): - request = build_get_kitten_request() - assert {"name": "Gatito", "likesMilk": True, "meows": True, "hisses": True, "eatsMiceYet": False} == send_request_json_response(request) - -def test_put_kitten(send_request_json_response): - request = build_put_kitten_request(json={"name": "Kitty", "likesMilk": False, "meows": True, "hisses": False, "eatsMiceYet": True}) - assert "Kitten was correct!" == send_request_json_response(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_non_string_enums.py b/test/vanilla/low-level/AcceptanceTests/test_non_string_enums.py deleted file mode 100644 index 108650e9015..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_non_string_enums.py +++ /dev/null @@ -1,57 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from nonstringenumslowlevel import NonStringEnumsClient -from nonstringenumslowlevel.rest import int, float - -import pytest -import json - -@pytest.fixture -def client(): - with NonStringEnumsClient() as client: - yield client - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_put_int_enum(send_request_json_response): - request = int.build_put_request(json=200) - assert send_request_json_response(request) == "Nice job posting an int enum" - -def test_get_int_enum(send_request_json_response): - request = int.build_get_request() - assert send_request_json_response(request) == 429 - -def test_put_float_enum(send_request_json_response): - request = float.build_put_request(json=200.4) - assert send_request_json_response(request) == "Nice job posting a float enum" - -def test_get_float_enum(send_request_json_response): - request = float.build_get_request() - assert send_request_json_response(request) == 429.1 diff --git a/test/vanilla/low-level/AcceptanceTests/test_number.py b/test/vanilla/low-level/AcceptanceTests/test_number.py deleted file mode 100644 index 92728f83d37..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_number.py +++ /dev/null @@ -1,139 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from decimal import Decimal -from azure.core.exceptions import DecodeError -import pytest - -from bodynumberlowlevel import AutoRestNumberTestService -from bodynumberlowlevel.rest import number - -import pytest - -@pytest.fixture -def client(): - with AutoRestNumberTestService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_big_float(send_request, send_request_json_response): - request = number.build_put_big_float_request(json=3.402823e+20) - send_request(request) - - request = number.build_get_big_float_request() - assert send_request_json_response(request) == 3.402823e+20 - -def test_small_float(send_request, send_request_json_response): - request = number.build_put_small_float_request(json=3.402823e-20) - send_request(request) - - request = number.build_get_small_float_request() - assert send_request_json_response(request) == 3.402823e-20 - -def test_big_double(send_request, send_request_json_response): - request = number.build_put_big_double_request(json=2.5976931e+101) - send_request(request) - - request = number.build_get_big_double_request() - assert send_request_json_response(request) == 2.5976931e+101 - -def test_small_double(send_request, send_request_json_response): - request = number.build_put_small_double_request(json=2.5976931e-101) - send_request(request) - - request = number.build_get_small_double_request() - assert send_request_json_response(request) == 2.5976931e-101 - -def test_big_double_negative_decimal(send_request, send_request_json_response): - request = number.build_put_big_double_negative_decimal_request() - send_request(request) - - request = number.build_get_big_double_negative_decimal_request() - assert send_request_json_response(request) == -99999999.99 - -def test_big_double_positive_decimal(send_request, send_request_json_response): - request = number.build_put_big_double_positive_decimal_request() - send_request(request) - - request = number.build_get_big_double_positive_decimal_request() - assert send_request_json_response(request) == 99999999.99 - -def test_big_decimal(send_request, send_request_json_response): - request = number.build_put_big_decimal_request(json=2.5976931e+101) - send_request(request) - - request = number.build_get_big_decimal_request() - assert send_request_json_response(request) == 2.5976931e+101 - -def test_small_decimal(send_request, send_request_json_response): - request = number.build_put_small_decimal_request(json=2.5976931e-101) - send_request(request) - - request = number.build_get_small_decimal_request() - assert send_request_json_response(request) == 2.5976931e-101 - -def test_get_big_decimal_negative_decimal(send_request, send_request_json_response): - request = number.build_put_big_decimal_negative_decimal_request() - - request = number.build_get_big_decimal_negative_decimal_request() - assert send_request_json_response(request) == -99999999.99 - -def test_get_big_decimal_positive_decimal(send_request, send_request_json_response): - request = number.build_put_big_decimal_positive_decimal_request() - send_request(request) - - request = number.build_get_big_decimal_positive_decimal_request() - assert send_request_json_response(request) == 99999999.99 - -def test_get_null(send_request): - request = number.build_get_null_request() - assert send_request(request).text() == '' - -def test_get_invalid_decimal(send_request): - request = number.build_get_invalid_decimal_request() - with pytest.raises(DecodeError): - send_request(request) - -def test_get_invalid_double(send_request): - request = number.build_get_invalid_double_request() - with pytest.raises(DecodeError): - send_request(request) - -def test_get_invalid_float(send_request): - request = number.build_get_invalid_float_request() - with pytest.raises(DecodeError): - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_object_type.py b/test/vanilla/low-level/AcceptanceTests/test_object_type.py deleted file mode 100644 index 6d0311c226f..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_object_type.py +++ /dev/null @@ -1,56 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from objecttypelowlevel import ObjectTypeClient -from objecttypelowlevel.rest import build_get_request, build_put_request -from azure.core.exceptions import HttpResponseError - -import pytest - -@pytest.fixture -def client(): - with ObjectTypeClient() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -def test_get_object(send_request): - request = build_get_request() - assert send_request(request).json() == {"message": "An object was successfully returned"} - -def test_put_object_success(send_request): - request = build_put_request(json={"foo": "bar"}) - assert send_request(request).text() == '' - -def test_put_object_fail(send_request): - request = build_put_request(json={"should": "fail"}) - with pytest.raises(HttpResponseError) as ex: - send_request(request) - assert ex.value.response.json()['message'] == 'The object you passed was incorrect' \ No newline at end of file diff --git a/test/vanilla/low-level/AcceptanceTests/test_parameterized_endpoint.py b/test/vanilla/low-level/AcceptanceTests/test_parameterized_endpoint.py deleted file mode 100644 index ba108dd7b0b..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_parameterized_endpoint.py +++ /dev/null @@ -1,42 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from parameterizedendpointlowlevel import ParmaterizedEndpointClient, rest - -@pytest.fixture -def client(): - with ParmaterizedEndpointClient(endpoint="http://localhost:3000") as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -def test_get(send_request): - request = rest.build_get_request() - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_required_optional.py b/test/vanilla/low-level/AcceptanceTests/test_required_optional.py deleted file mode 100644 index 2c23a65dd17..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_required_optional.py +++ /dev/null @@ -1,193 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import sys -import io -from azure.core.exceptions import HttpResponseError - -from requiredoptionallowlevel import AutoRestRequiredOptionalTestService -from requiredoptionallowlevel.rest import implicit, explicit - -import pytest - -@pytest.fixture -def client_required(): - with AutoRestRequiredOptionalTestService( - "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 send_request_required_client(client_required, base_send_request): - def _send_request(request): - return base_send_request(client_required, request) - return _send_request - -@pytest.fixture -def client(): - with AutoRestRequiredOptionalTestService( - "required_path", - "required_query", - ) as client: - client._config.required_global_path = None - client._config.required_global_query = None - yield client - -@pytest.fixture -def send_request_client(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request -# NOTE: in the LLC version, we can't raise as many ValidationErrors as the high level convenience layer does. -# This is because we're not serializing bodies at all, so msrest doesn't have a chance to throw the validation error - - -# These clients have a required global path and query -def test_put_optional(send_request_required_client): - request = implicit.build_put_optional_query_request(query_parameter=None) - send_request_required_client(request) - - request = implicit.build_put_optional_body_request(json=None) - send_request_required_client(request) - - request = implicit.build_put_optional_header_request(query_parameter=None) - send_request_required_client(request) - -def test_get_optional_global_query(send_request_required_client): - request = implicit.build_get_optional_global_query_request(optional_global_query=None) - send_request_required_client(request) - -def test_post_optional_integer(send_request_required_client): - request = explicit.build_post_optional_integer_parameter_request(json=None) - send_request_required_client(request) - - - request = explicit.build_post_optional_integer_property_request(json={"value": None}) - send_request_required_client(request) - - request = explicit.build_post_optional_integer_header_request(header_parameter=None) - send_request_required_client(request) - -def test_post_optional_string(send_request_required_client): - request = explicit.build_post_optional_string_parameter_request(content=None) - send_request_required_client(request) - - - request = explicit.build_post_optional_string_property_request(json={"value": None}) - send_request_required_client(request) - - request = explicit.build_post_optional_string_header_request(body_parameter=None) - send_request_required_client(request) - -def test_post_optional_class(send_request_required_client): - request = explicit.build_post_optional_class_parameter_request() - send_request_required_client(request) - - request = explicit.build_post_optional_class_property_request(json={"value": None}) - send_request_required_client(request) - -def test_post_optional_array(send_request_required_client): - request = explicit.build_post_optional_array_parameter_request(json=None) - send_request_required_client(request) - - request = explicit.build_post_optional_array_property_request(json={"value": None}) - send_request_required_client(request) - - request = explicit.build_post_optional_array_header_request(header_parameter=None) - send_request_required_client(request) - -def test_implicit_get_required(send_request_client): - with pytest.raises(ValueError): - request = implicit.build_get_required_path_request(path_parameter=None) - send_request_client(request) - - with pytest.raises(ValueError): - request = implicit.build_get_required_global_path_request(required_global_path=None) - send_request_client(request) - - with pytest.raises(ValueError): - request = implicit.build_get_required_global_query_request(required_global_query=None) - send_request_client(request) - -def test_post_required_string(send_request_client): - with pytest.raises(ValueError): - request = explicit.build_post_required_string_header_request(header_parameter=None) - send_request_client(request) - - with pytest.raises(HttpResponseError) as ex: - request = explicit.build_post_required_string_parameter_request(content=None) - send_request_client(request) - - assert "Not Found" in str(ex.value) - - with pytest.raises(HttpResponseError)as ex: - request = explicit.build_post_required_string_property_request(json={"value": None}) - send_request_client(request) - assert "Not Found" in str(ex.value) - -def test_post_required_array(send_request_client): - with pytest.raises(TypeError): - request = explicit.build_post_required_array_header_request(header_parameter=None) - send_request_client(request) - - with pytest.raises(HttpResponseError) as ex: - request = explicit.build_post_required_array_parameter_request() - send_request_client(request) - assert "Not Found" in str(ex.value) - - with pytest.raises(HttpResponseError) as ex: - request = explicit.build_post_required_array_property_request(json={"value": None}) - send_request_client(request) - assert "Not Found" in str(ex.value) - -def test_post_required_class(send_request_client): - with pytest.raises(HttpResponseError) as ex: - request = explicit.build_post_required_class_parameter_request() - send_request_client(request) - assert "Not Found" in str(ex.value) - - with pytest.raises(HttpResponseError) as ex: - request = explicit.build_post_required_class_property_request(json={"value": None}) - send_request_client(request) - assert "Not Found" in str(ex.value) - -def test_explict_put_optional_binary_body(send_request_client): - request = explicit.build_put_optional_binary_body_request() - send_request_client(request) - -def test_explict_put_required_binary_body(client): - test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') - with io.BytesIO(test_bytes) as stream_data: - request = explicit.build_put_required_binary_body_request(content=stream_data) - client.send_request(request, stream=True) - -def test_implicit_put_optional_binary_body(send_request_client): - request = explicit.build_put_optional_binary_body_request() - send_request_client(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_reserved_words.py b/test/vanilla/low-level/AcceptanceTests/test_reserved_words.py deleted file mode 100644 index 289fc91966d..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_reserved_words.py +++ /dev/null @@ -1,75 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from reservedwordslowlevel import ReservedWordsClient -from reservedwordslowlevel.rest import import_operations -from reservedwordslowlevel.rest import ( - build_operation_with_content_param_request, - build_operation_with_data_param_request, - build_operation_with_files_param_request, - build_operation_with_json_param_request, - build_operation_with_url_request, -) - -@pytest.fixture -def client(): - with ReservedWordsClient() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -def test_operation_group_import(send_request): - request = import_operations.build_operation_one_request(parameter1="foo") - send_request(request) - -def test_operation_with_content_param(send_request): - request = build_operation_with_content_param_request(content=b"hello, world", headers={"Content-Type": "application/octet-stream"}) - send_request(request) - -def test_operation_with_json_param(send_request): - request = build_operation_with_json_param_request(json={"hello": "world"}) - send_request(request) - -@pytest.mark.skip("We don't do urlencoded bodies anymore") -def test_operation_with_data_param(send_request): - request = build_operation_with_data_param_request(data={"data": "hello", "world": "world"}) - send_request(request) - -@pytest.mark.skip("We don't do multipart bodies anymore") -def test_operation_with_files_param(send_request): - request = build_operation_with_files_param_request(files={ - "file_name": "my.txt", - "files": b'bytes' - }) - send_request(request) - -def test_operation_with_url(send_request): - request = build_operation_with_url_request("foo", header_parameters="x-ms-header", query_parameters=["one", "two"]) - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_security.py b/test/vanilla/low-level/AcceptanceTests/test_security.py deleted file mode 100644 index 6dadafbe1c8..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_security.py +++ /dev/null @@ -1,50 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -from securitykeyswaggerlowlevel import AutorestSecurityKey -from securityaadswaggerlowlevel import AutorestSecurityAad - -from azure.core.credentials import AzureKeyCredential -from azure.core.pipeline.policies import AzureKeyCredentialPolicy -from azure.core.pipeline.policies import BearerTokenCredentialPolicy - -def test_security_aad_swagger(credential): - from securityaadswaggerlowlevel.rest import build_head_request - - client = AutorestSecurityAad(credential=credential) - assert isinstance(client._config.authentication_policy, BearerTokenCredentialPolicy) - request = build_head_request() - response = client.send_request(request, enforce_https=False) - response.raise_for_status() - -def test_security_key_swagger(): - from securitykeyswaggerlowlevel.rest import build_head_request - - # 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')) - assert isinstance(client._config.authentication_policy, AzureKeyCredentialPolicy) - request = build_head_request() - response = client.send_request(request) - response.raise_for_status() diff --git a/test/vanilla/low-level/AcceptanceTests/test_send_request.py b/test/vanilla/low-level/AcceptanceTests/test_send_request.py deleted file mode 100644 index 95d2e5761f1..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_send_request.py +++ /dev/null @@ -1,171 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import io -import json - -from azure.core.rest import HttpRequest - -from os.path import dirname, pardir, join, realpath -import pytest - -cwd = dirname(realpath(__file__)) - - -class TestSendRequest(object): - - def test_send_request_with_body_get_model_deserialize(self): - from bodycomplexlowlevel import AutoRestComplexTestService - - client = AutoRestComplexTestService() - - request = HttpRequest("GET", "/complex/inheritance/valid", - ) - - 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'] - - def test_send_request_with_stream_get_direct_json(self): - from bodycomplexlowlevel import AutoRestComplexTestService - - client = AutoRestComplexTestService() - - request = HttpRequest("GET", "/complex/inheritance/valid", - headers={ - 'Accept': 'application/json' - }, - ) - - with client.send_request(request, stream=True) as response: - response.raise_for_status() - 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'] - - def test_send_request_with_body_put_json_dumps(self): - from bodycomplexlowlevel import AutoRestComplexTestService - - client = AutoRestComplexTestService() - - siamese_body = { - "id": 2, - "name": "Siameeee", - "color": "green", - "hates": - [ - { - "id": 1, - "name": "Potato", - "food": "tomato" - }, - { - "id": -1, - "name": "Tomato", - "food": "french fries" - } - ], - "breed": "persian" - } - - request = HttpRequest("PUT", "/complex/inheritance/valid", - json=siamese_body - ) - assert request.headers['Content-Type'] == "application/json" - response = client.send_request(request) - response.raise_for_status() - assert response.status_code == 200 - - def test_send_request_get_stream(self): - from bodyfilelowlevel import AutoRestSwaggerBATFileService - - client = AutoRestSwaggerBATFileService(connection_data_block_size=1000) - file_length = 0 - with io.BytesIO() as file_handle: - - request = HttpRequest("GET", "/files/stream/nonempty", - headers={ - 'Accept': 'image/png, application/json' - }, - ) - - with client.send_request(request, stream=True) as response: - response.raise_for_status() - for data in response.iter_bytes(): - file_length += len(data) - file_handle.write(data) - - 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: - sample_data = hash(data.read()) - assert sample_data == hash(file_handle.getvalue()) - - def test_send_request_put_stream(self): - from bodyformdatalowlevel import AutoRestSwaggerBATFormDataService - - client = AutoRestSwaggerBATFormDataService() - - test_string = "Upload file test case" - test_bytes = bytearray(test_string, encoding='utf-8') - with io.BytesIO(test_bytes) as stream_data: - request = HttpRequest("PUT", '/formdata/stream/uploadfile', - content=stream_data, - headers={"Content-Type": "application/octet-stream"} - ) - with client.send_request(request, stream=True) as response: - response.raise_for_status() - - def test_send_request_full_url(self): - from bodycomplexlowlevel import AutoRestComplexTestService - - client = AutoRestComplexTestService(endpoint="http://fakeUrl") - - 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'] diff --git a/test/vanilla/low-level/AcceptanceTests/test_string_tests.py b/test/vanilla/low-level/AcceptanceTests/test_string_tests.py deleted file mode 100644 index 70b17298554..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_string_tests.py +++ /dev/null @@ -1,171 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from azure.core.exceptions import HttpResponseError - -from bodystringlowlevel import AutoRestSwaggerBATService -from bodystringlowlevel.rest import string, enum -import pytest -from bodystringlowlevel._serialization import Serializer, Deserializer -from base64 import b64decode - -@pytest.fixture -def client(): - with AutoRestSwaggerBATService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -def test_null(send_request): - request = string.build_get_null_request() - assert send_request(request).text() == '' - - request = string.build_put_null_request(content=None) - send_request(request) - -def test_empty(send_request, send_request_json_response): - request = string.build_get_empty_request() - assert "" == send_request_json_response(request) - # changing this behavior because of this pr being merged: https://github.com/Azure/autorest.testserver/pull/145/files - request = string.build_put_empty_request() - send_request(request) - -def test_mbcs(send_request, send_request_json_response): - try: - test_str = ( - "\xe5\x95\x8a\xe9\xbd\x84\xe4\xb8\x82\xe7\x8b\x9b\xe7\x8b" - "\x9c\xef\xa7\xb1\xef\xa4\xac\xef\xa7\xb1\xef\xa8\x8c\xef" - "\xa8\xa9\xcb\x8a\xe3\x80\x9e\xe3\x80\xa1\xef\xbf\xa4\xe2" - "\x84\xa1\xe3\x88\xb1\xe2\x80\x90\xe3\x83\xbc\xef\xb9\xa1" - "\xef\xb9\xa2\xef\xb9\xab\xe3\x80\x81\xe3\x80\x93\xe2\x85" - "\xb0\xe2\x85\xb9\xe2\x92\x88\xe2\x82\xac\xe3\x88\xa0\xe3" - "\x88\xa9\xe2\x85\xa0\xe2\x85\xab\xef\xbc\x81\xef\xbf\xa3" - "\xe3\x81\x81\xe3\x82\x93\xe3\x82\xa1\xe3\x83\xb6\xce\x91" - "\xef\xb8\xb4\xd0\x90\xd0\xaf\xd0\xb0\xd1\x8f\xc4\x81\xc9" - "\xa1\xe3\x84\x85\xe3\x84\xa9\xe2\x94\x80\xe2\x95\x8b\xef" - "\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') - - except AttributeError: - test_str = ( - b"\xe5\x95\x8a\xe9\xbd\x84\xe4\xb8\x82\xe7\x8b\x9b\xe7\x8b" - b"\x9c\xef\xa7\xb1\xef\xa4\xac\xef\xa7\xb1\xef\xa8\x8c\xef" - b"\xa8\xa9\xcb\x8a\xe3\x80\x9e\xe3\x80\xa1\xef\xbf\xa4\xe2" - b"\x84\xa1\xe3\x88\xb1\xe2\x80\x90\xe3\x83\xbc\xef\xb9\xa1" - b"\xef\xb9\xa2\xef\xb9\xab\xe3\x80\x81\xe3\x80\x93\xe2\x85" - b"\xb0\xe2\x85\xb9\xe2\x92\x88\xe2\x82\xac\xe3\x88\xa0\xe3" - b"\x88\xa9\xe2\x85\xa0\xe2\x85\xab\xef\xbc\x81\xef\xbf\xa3" - b"\xe3\x81\x81\xe3\x82\x93\xe3\x82\xa1\xe3\x83\xb6\xce\x91" - b"\xef\xb8\xb4\xd0\x90\xd0\xaf\xd0\xb0\xd1\x8f\xc4\x81\xc9" - b"\xa1\xe3\x84\x85\xe3\x84\xa9\xe2\x94\x80\xe2\x95\x8b\xef" - 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') - - request = string.build_get_mbcs_request() - assert test_str == send_request_json_response(request) - - request = string.build_put_mbcs_request() - send_request(request) - -def test_whitespace(send_request, send_request_json_response): - test_str = " Now is the time for all good men to come to the aid of their country " - request = string.build_get_whitespace_request() - assert test_str == send_request_json_response(request) - - request = string.build_put_whitespace_request() - send_request(request) - -def test_get_not_provided(send_request): - request = string.build_get_not_provided_request() - assert send_request(request).text() == '' - -def test_enum_not_expandable(send_request, send_request_json_response): - request = enum.build_get_not_expandable_request() - assert "red color" == send_request_json_response(request) - - request = enum.build_put_not_expandable_request(json='red color') - send_request(request) - - request = enum.build_put_not_expandable_request(json='red color') - send_request(request) - # 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. - - request = enum.build_put_not_expandable_request(json='not a color') - with pytest.raises(HttpResponseError): - send_request(request) - -def test_get_base64_encoded(send_request): - request = string.build_get_base64_encoded_request() - assert b64decode(send_request(request).text()) == 'a string that gets encoded with base64'.encode() - -def test_base64_url_encoded(send_request): - # the b64 encoding and decoding is taken from msrest - request = string.build_get_base64_url_encoded_request() - response = send_request(request).text() - response = Deserializer.deserialize_base64(response) - assert response == 'a string that gets encoded with base64url'.encode() - - content = Serializer.serialize_base64('a string that gets encoded with base64url'.encode()) - request = string.build_put_base64_url_encoded_request(json=content) - send_request(request) - -def test_get_null_base64_url_encoded(send_request): - request = string.build_get_null_base64_url_encoded_request() - assert send_request(request).text() == '' - -def test_enum_referenced(send_request, send_request_json_response): - request = enum.build_put_referenced_request(json='red color') - send_request(request) - - request = enum.build_put_referenced_request(json="red color") - send_request(request) - - request = enum.build_get_referenced_request() - assert send_request_json_response(request) == 'red color' - -def test_enum_referenced_constant(send_request, send_request_json_response): - request = enum.build_put_referenced_request(json="red color") - send_request(request) - - request = enum.build_get_referenced_constant_request() - response = send_request_json_response(request) - assert response == {'field1': 'Sample String'} # there's no constant on the response, so just getting field1 diff --git a/test/vanilla/low-level/AcceptanceTests/test_time.py b/test/vanilla/low-level/AcceptanceTests/test_time.py deleted file mode 100644 index 4c533554861..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_time.py +++ /dev/null @@ -1,50 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -import datetime - -from bodytimelowlevel import AutoRestTimeTestService -from bodytimelowlevel.rest import time -import pytest - -@pytest.fixture -def client(): - with AutoRestTimeTestService() as client: - yield client - -def test_get(client): - request = time.build_get_request() - response = client.send_request(request) - response.raise_for_status() - assert datetime.datetime.strptime(response.json(), '%H:%M:%S').time() == datetime.time(11, 34, 56) - - -def test_put(client): - request = time.build_put_request(json=datetime.time(8, 7, 56).strftime("%H:%M:%S")) - response = client.send_request(request) - response.raise_for_status() - assert response.json() == "Nice job posting time" diff --git a/test/vanilla/low-level/AcceptanceTests/test_url.py b/test/vanilla/low-level/AcceptanceTests/test_url.py deleted file mode 100644 index 32e6f48ee7b..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_url.py +++ /dev/null @@ -1,347 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -from datetime import datetime -from urllowlevel import AutoRestUrlTestService -from urllowlevel.rest import queries, paths, path_items -from urlmulticollectionformatlowlevel import AutoRestUrlMutliCollectionFormatTestService -from urlmulticollectionformatlowlevel.rest import queries as multiqueries - -import pytest - -@pytest.fixture -def client(): - with AutoRestUrlTestService('') as client: - yield client - -@pytest.fixture -def multi_client(): - with AutoRestUrlMutliCollectionFormatTestService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def make_multi_request(multi_client, base_send_request): - def _send_request(request): - return base_send_request(multi_client, request) - return _send_request - -@pytest.fixture -def test_array_query(): - return ["ArrayQuery1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] - -def test_byte_empty_and_null(send_request): - request = paths.build_byte_empty_request() - send_request(request) - - with pytest.raises(ValueError): - paths.build_byte_null_request(None) - -def test_byte_multi_byte(send_request): - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') - request = paths.build_byte_multi_byte_request(u_bytes) - send_request(request) - -def test_date_null(send_request): - with pytest.raises(ValueError): - paths.build_date_null_request(None) - -def test_date_time_null(send_request): - with pytest.raises(ValueError): - paths.build_date_time_null_request(None) - -def test_date_time_valid(send_request): - request = paths.build_date_time_valid_request() - send_request(request) - -def test_date_valid(send_request): - request = paths.build_date_valid_request() - send_request(request) - -def test_unix_time_url(send_request): - request = paths.build_unix_time_url_request(datetime(year=2016, month=4, day=13)) - send_request(request) - -def test_double_decimal(send_request): - request = paths.build_double_decimal_negative_request() - send_request(request) - request = paths.build_double_decimal_positive_request() - send_request(request) - -def test_float_scientific(send_request): - request = paths.build_float_scientific_negative_request() - send_request(request) - - request = paths.build_float_scientific_positive_request() - send_request(request) - -def test_get_boolean(send_request): - request = paths.build_get_boolean_false_request() - send_request(request) - - request = paths.build_get_boolean_true_request() - send_request(request) - -def test_int(send_request): - request = paths.build_get_int_negative_one_million_request() - send_request(request) - - request = paths.build_get_int_one_million_request() - send_request(request) - -def test_get_long(send_request): - request = paths.build_get_negative_ten_billion_request() - send_request(request) - - request = paths.build_get_ten_billion_request() - send_request(request) - -def test_string_empty_and_null(send_request): - request = paths.build_string_empty_request() - send_request(request) - - with pytest.raises(ValueError): - paths.build_string_null_request(None) - -def test_array_csv_in_path(send_request): - test_array = ["ArrayPath1", r"begin!*'();:@ &=+$,/?#[]end", None, ""] - request = paths.build_array_csv_in_path_request(test_array) - send_request(request) - -def test_string_url_encoded(send_request): - request = paths.build_string_url_encoded_request() - send_request(request) - -def test_paths_unicode(send_request): - request = paths.build_string_unicode_request() - send_request(request) - -def test_string_url_non_encoded(send_request): - request = paths.build_string_url_non_encoded_request() - send_request(request) - -def test_enum_valid(send_request): - request = paths.build_enum_valid_request("green color") - send_request(request) - -def test_enum_null(send_request): - with pytest.raises(ValueError): - paths.build_enum_null_request(None) - -def test_base64_url(send_request): - request = paths.build_base64_url_request("lorem".encode()) - send_request(request) - -def test_queries_byte(send_request): - request = queries.build_byte_empty_request() - send_request(request) - - u_bytes = bytearray(u"\u554A\u9F44\u4E02\u72DB\u72DC\uF9F1\uF92C\uF9F1\uFA0C\uFA29", encoding='utf-8') - request = queries.build_byte_multi_byte_request(byte_query=u_bytes) - send_request(request) - - request = queries.build_byte_null_request() - send_request(request) - -def test_queries_date(send_request): - request = queries.build_date_null_request() - send_request(request) - - request = queries.build_date_valid_request() - send_request(request) - -def test_queries_date_time(send_request): - request = queries.build_date_time_null_request() - send_request(request) - - request = queries.build_date_time_valid_request() - send_request(request) - -def test_queries_double(send_request): - request = queries.build_double_null_request() - send_request(request) - - request = queries.build_double_decimal_negative_request() - send_request(request) - - request = queries.build_double_decimal_positive_request() - send_request(request) - -def test_queries_float_scientific(send_request): - request = queries.build_float_scientific_negative_request() - send_request(request) - - request = queries.build_float_scientific_positive_request() - send_request(request) - request = queries.build_float_null_request() - send_request(request) - -def test_queries_boolean(send_request): - request = queries.build_get_boolean_false_request() - send_request(request) - - request = queries.build_get_boolean_true_request() - send_request(request) - - request = queries.build_get_boolean_null_request() - send_request(request) - -def test_queries_int(send_request): - request = queries.build_get_int_negative_one_million_request() - send_request(request) - - request = queries.build_get_int_one_million_request() - send_request(request) - - request = queries.build_get_int_null_request() - send_request(request) - -def test_queries_long(send_request): - request = queries.build_get_negative_ten_billion_request() - send_request(request) - - request = queries.build_get_ten_billion_request() - send_request(request) - - request = queries.build_get_long_null_request() - send_request(request) - -def test_queries_string(send_request): - request = queries.build_string_empty_request() - send_request(request) - - request = queries.build_string_null_request() - send_request(request) - - request = queries.build_string_url_encoded_request() - send_request(request) - -def test_queries_enum(send_request): - request = queries.build_enum_valid_request(enum_query="green color") - send_request(request) - - request = queries.build_enum_null_request(enum_query=None) - send_request(request) - -def test_queries_unicode(send_request): - request = queries.build_string_unicode_request() - send_request(request) - -def test_array_string_csv(send_request, test_array_query): - request = queries.build_array_string_csv_empty_request(array_query=[]) - send_request(request) - - request = queries.build_array_string_csv_null_request(array_query=None) - send_request(request) - - request = queries.build_array_string_csv_valid_request(array_query=test_array_query) - send_request(request) - -def test_array_string_miscellaneous(send_request, test_array_query): - request = queries.build_array_string_pipes_valid_request(array_query=test_array_query) - send_request(request) - - request = queries.build_array_string_ssv_valid_request(array_query=test_array_query) - send_request(request) - - request = queries.build_array_string_tsv_valid_request(array_query=test_array_query) - send_request(request) - -def test_array_string_multi(make_multi_request, test_array_query): - request = multiqueries.build_array_string_multi_empty_request(array_query=[]) - make_multi_request(request) - - request = multiqueries.build_array_string_multi_null_request() - make_multi_request(request) - - request = multiqueries.build_array_string_multi_valid_request(array_query=test_array_query) - make_multi_request(request) - -def test_array_string_no_collection_format(send_request): - request = queries.build_array_string_no_collection_format_empty_request(array_query=['hello', 'nihao', 'bonjour']) - send_request(request) - -def test_get_all_with_values(send_request): - # In LLC, we have to pass in global variables to individual operations; we don't have access to the client in the request builders - global_string_path = "globalStringPath" - global_string_query = "globalStringQuery" - - request = path_items.build_get_all_with_values_request( - path_item_string_path="pathItemStringPath", - global_string_path=global_string_path, - local_string_path="localStringPath", - path_item_string_query="pathItemStringQuery", - global_string_query=global_string_query, - local_string_query="localStringQuery", - ) - - send_request(request) - -def test_get_global_and_local_query_null(send_request): - # In LLC, we have to pass in global variables to individual operations; we don't have access to the client in the request builders - global_string_path = "globalStringPath" - - request = path_items.build_get_global_and_local_query_null_request( - path_item_string_path="pathItemStringPath", - global_string_path=global_string_path, - local_string_path="localStringPath", - path_item_string_query="pathItemStringQuery", - global_string_query=None - ) - send_request(request) - -def test_get_global_query_null(send_request): - # In LLC, we have to pass in global variables to individual operations; we don't have access to the client in the request builders - global_string_path = "globalStringPath" - - request = path_items.build_get_global_query_null_request( - path_item_string_path="pathItemStringPath", - global_string_path=global_string_path, - local_string_path="localStringPath", - path_item_string_query="pathItemStringQuery", - local_string_query="localStringQuery", - ) - send_request(request) - -def test_get_local_path_item_query_null(send_request): - # In LLC, we have to pass in global variables to individual operations; we don't have access to the client in the request builders - global_string_path = "globalStringPath" - global_string_query = "globalStringQuery" - - request = path_items.build_get_local_path_item_query_null_request( - path_item_string_path="pathItemStringPath", - global_string_path=global_string_path, - local_string_path="localStringPath", - path_item_string_query=None, - global_string_query=global_string_query, - local_string_query=None, - ) - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_urlencoded.py b/test/vanilla/low-level/AcceptanceTests/test_urlencoded.py deleted file mode 100644 index fdd214c94f1..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_urlencoded.py +++ /dev/null @@ -1,64 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import pytest -from bodyformurlencodeddatalowlevel import BodyFormsDataURLEncoded -from bodyformurlencodeddatalowlevel.rest import formdataurlencoded - -@pytest.fixture -def client(): - with BodyFormsDataURLEncoded() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.mark.skip("We don't do urlencoded bodies anymore.") -def test_update_pet_with_form(send_request): - request = formdataurlencoded.build_update_pet_with_form_request( - pet_id=1, - data={ - "pet_type": "dog", - "pet_food": "meat", - "pet_age": 42, - "name": "Fido", - } - ) - send_request(request) - -@pytest.mark.skip("We don't do urlencoded bodies anymore.") -def test_partial_constant_body(send_request): - request = formdataurlencoded.build_partial_constant_body_request( - data={ - "access_token": "foo", - "grant_type": "access_token", - "service": "bar" - } - ) - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_validation.py b/test/vanilla/low-level/AcceptanceTests/test_validation.py deleted file mode 100644 index 22c5f7a6f10..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_validation.py +++ /dev/null @@ -1,85 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import sys - -from azure.core.exceptions import HttpResponseError -from validationlowlevel import AutoRestValidationTest -from validationlowlevel.rest import * - -import pytest - -@pytest.fixture -def client(): - with AutoRestValidationTest("abc123") as client: - client.api_version = "12-34-5678" - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_json_response(client, base_send_request_json_response): - def _send_request(request): - return base_send_request_json_response(client, request) - return _send_request - -@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 { - 'child': { - 'constProperty': 'constant' - }, - 'constChild': { - 'constProperty': 'constant', - 'constProperty2': 'constant2' - }, - 'constInt': 0, - 'constString': 'constant', - 'constStringAsEnum': 'constant_string_as_enum' - } - -def test_with_constant_in_path(send_request): - request = build_get_with_constant_in_path_request() - send_request(request) - -def test_post_with_constant_in_body(send_request_json_response, constant_body): - request = build_post_with_constant_in_body_request(json=constant_body) - product = send_request_json_response(request) - assert product is not None - -# 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 HttpResponseError -def test_fakedpath_validation(send_request): - with pytest.raises(HttpResponseError): - request = build_validation_of_method_parameters_request(subscription_id="abc123", resource_group_name="1", id=100) - send_request(request) \ No newline at end of file diff --git a/test/vanilla/low-level/AcceptanceTests/test_xml.py b/test/vanilla/low-level/AcceptanceTests/test_xml.py deleted file mode 100644 index 9a609da074a..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_xml.py +++ /dev/null @@ -1,240 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import xml.etree.ElementTree as ET -from xmlservicelowlevel import AutoRestSwaggerBATXMLService -from xmlservicelowlevel.rest import xml -from base64 import b64decode - -import pytest - - -@pytest.fixture -def client(): - with AutoRestSwaggerBATXMLService() as client: - yield client - -@pytest.fixture -def send_request(client, base_send_request): - def _send_request(request): - return base_send_request(client, request) - return _send_request - -@pytest.fixture -def send_request_text_response(client, base_send_request): - def _send_request(request): - return base_send_request(client, request).text() - return _send_request - -def test_json_xml(send_request): - request = xml.build_json_input_request(json={"id": 42}) - send_request(request) - - request = xml.build_json_output_request() - assert send_request(request).json()['id'] == 42 - -def test_simple(send_request, send_request_text_response): - # Slideshow - - request = xml.build_get_simple_request() - slideshow = ET.fromstring(send_request_text_response(request)) - assert slideshow.attrib['title'] == "Sample Slide Show" - assert slideshow.attrib['date'] == "Date of publication" - assert slideshow.attrib['author'] == "Yours Truly" - slides = list(slideshow.iterfind('slide')) - assert len(slides) == 2 - - slide1 = slides[0] - assert slide1.attrib['type'] == "all" - assert next(slide1.iterfind('title')).text == "Wake up to WonderWidgets!" - assert len(list(slide1.iterfind('item'))) == 0 - - slide2 = slides[1] - assert slide2.attrib['type'] == "all" - assert next(slide2.iterfind('title')).text == "Overview" - items = list(slide2.iterfind('item')) - assert len(items) == 3 - assert items[0].text == "Why WonderWidgets are great" - assert items[1].text == None - assert items[2].text == "Who buys WonderWidgets" - - request = xml.build_put_simple_request(content=slideshow, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_empty_child_element(send_request, send_request_text_response): - request = xml.build_get_empty_child_element_request() - banana = ET.fromstring(send_request_text_response(request)) - assert banana.attrib == {}# That's the point of this test, it was an empty node. - request = xml.build_put_empty_child_element_request(content=banana, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_empty_root_list(send_request, send_request_text_response): - request = xml.build_get_empty_root_list_request() - empty = ET.fromstring(send_request_text_response(request)) - assert empty.tag == 'bananas' - assert empty.attrib == {} - assert send_request_text_response(request) == "\n" - request = xml.build_put_empty_root_list_request(content=empty, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_root_list_single_item(send_request, send_request_text_response): - request = xml.build_get_root_list_single_item_request() - xml_body = ET.fromstring(send_request_text_response(request)) - bananas = list(xml_body.iterfind('banana')) - assert len(bananas) == 1 - assert next(bananas[0].iterfind('name')).text == "Cavendish" - request = xml.build_put_root_list_single_item_request(content=xml_body, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_root_list(send_request, send_request_text_response): - request = xml.build_get_root_list_request() - xml_body = ET.fromstring(send_request_text_response(request)) - bananas = list(xml_body.iterfind('banana')) - assert len(bananas) == 2 - request = xml.build_put_root_list_request(content=xml_body, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_empty_wrapped_lists(send_request, send_request_text_response): - request = xml.build_get_empty_wrapped_lists_request() - bananas = ET.fromstring(send_request_text_response(request)) - """ - - - - `; - """ - good_apples = [a for a in bananas.iterfind('GoodApples') if a.text] - assert len(good_apples) == 0 - bad_apples = [a for a in bananas.iterfind('BadApples') if a.text] - assert len(bad_apples) == 0 - request = xml.build_put_empty_wrapped_lists_request(content=bananas, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_get_empty(send_request, send_request_text_response): - request = xml.build_get_empty_list_request() - slideshow = ET.fromstring(send_request_text_response(request)) - request = xml.build_put_empty_list_request(content=slideshow, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_wrapped_lists(send_request, send_request_text_response): - request = xml.build_get_wrapped_lists_request() - bananas = ET.fromstring(send_request_text_response(request)) - good_apples = bananas.find('GoodApples') - assert [a.text for a in good_apples.iterfind('Apple')] == ['Fuji', 'Gala'] - - bad_apples = bananas.find('BadApples') - assert [a.text for a in bad_apples.iterfind('Apple')] == ['Red Delicious'] - request = xml.build_put_wrapped_lists_request(content=bananas, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_complex_types(send_request, send_request_text_response): - request = xml.build_get_complex_type_ref_no_meta_request() - root = ET.fromstring(send_request_text_response(request)) - ref_to_model = root.find('RefToModel') - assert ref_to_model.find('ID').text == "myid" - request = xml.build_put_complex_type_ref_no_meta_request(content=root, headers={"Content-Type": "application/xml"}) - send_request(request) - - request = xml.build_get_complex_type_ref_with_meta_request() - root = ET.fromstring(send_request_text_response(request)) - ref_to_model = root.find('XMLComplexTypeWithMeta') - assert ref_to_model.find('ID').text == "myid" - request = xml.build_put_complex_type_ref_with_meta_request(content=root, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_list_containers(send_request_text_response): - request = xml.build_list_containers_request() - xml_body = ET.fromstring(send_request_text_response(request)) - containers = xml_body.find('Containers') - container_list = list(containers.iterfind('Container')) - assert len(container_list) == 3 - -def test_list_blobs(send_request_text_response): - request = xml.build_list_blobs_request() - xml_body = ET.fromstring(send_request_text_response(request)) - blobs_xml_body = xml_body.find('Blobs') - blobs = list(blobs_xml_body.iterfind('Blob')) - assert len(blobs) == 5 - assert blobs_xml_body.find('BlobPrefix') is None - blob = blobs[0] - assert blob.find('Name').text == "blob1.txt" - properties = blob.find('Properties') - assert properties.find('Last-Modified').text == 'Wed, 09 Sep 2009 09:20:02 GMT' - assert properties.find('Etag').text == "0x8CBFF45D8A29A19" - assert properties.find('Content-Length').text == "100" - assert properties.find('Content-Type').text == "text/html" - # Check that an empty field in the XML is empty string - assert properties.find('Content-Encoding').text is None - assert properties.find('Content-Language').text == "en-US" - assert properties.find('Content-MD5').text is None - assert properties.find('Cache-Control').text == "no-cache" - assert properties.find('BlobType').text == "BlockBlob" - # Check that a field NOT in the XML is None - assert properties.find('Destination-Snapshot') is None - metadata_body = blob.find('Metadata') - assert metadata_body.find("Color").text == "blue" - assert metadata_body.find("BlobNumber").text == "01" - assert metadata_body.find("SomeMetadataName").text == "SomeMetadataValue" - -def test_service_properties(send_request, send_request_text_response): - request = xml.build_get_service_properties_request() - properties = ET.fromstring(send_request_text_response(request)) - assert properties.find('HourMetrics') is not None - assert properties.find('MinuteMetrics') is not None - request = xml.build_put_service_properties_request(content=properties, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_acls(send_request, send_request_text_response): - request = xml.build_get_acls_request() - acls = ET.fromstring(send_request_text_response(request)) - signed_identifiers = list(acls.iterfind('SignedIdentifier')) - assert len(signed_identifiers) == 1 - assert signed_identifiers[0].find('Id').text == 'MTIzNDU2Nzg5MDEyMzQ1Njc4OTAxMjM0NTY3ODkwMTI=' - request = xml.build_put_acls_request(content=acls, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_xms_text(send_request_text_response): - request = xml.build_get_xms_text_request() - xml_object = ET.fromstring(send_request_text_response(request)) - assert xml_object.attrib['language'] == "english" - assert xml_object.text == "I am text" - -def test_bytes(send_request_text_response, send_request): - request = xml.build_get_bytes_request() - bytes_object = ET.fromstring(send_request_text_response(request)) - assert bytes_object.tag == 'ModelWithByteProperty' - assert b64decode(bytes_object.find('Bytes').text) == b"Hello world" - - request = xml.build_put_binary_request(content=bytes_object, headers={"Content-Type": "application/xml"}) - send_request(request) - -def test_url(send_request_text_response, send_request): - request = xml.build_get_uri_request() - url_object = ET.fromstring(send_request_text_response(request)) - assert url_object.tag == 'ModelWithUrlProperty' - assert url_object.find('Url').text == 'https://myaccount.blob.core.windows.net/' - - request = xml.build_put_uri_request(content=url_object, headers={"Content-Type": "application/xml"}) - send_request(request) diff --git a/test/vanilla/low-level/AcceptanceTests/test_zzz.py b/test/vanilla/low-level/AcceptanceTests/test_zzz.py deleted file mode 100644 index dc2b26d2eb0..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/test_zzz.py +++ /dev/null @@ -1,120 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import sys -import datetime -import os -import platform -import warnings - -from reportlowlevel import AutoRestReportService, rest - - -class TestAcceptance(object): - - def test_ensure_coverage(self): - client = AutoRestReportService() - request = rest.build_get_report_request(qualifier=platform.python_version()) - report = client.send_request(request).json() - - request = rest.build_get_optional_report_request(qualifier=platform.python_version()) - optional_report = client.send_request(request).json() - - # Add tests that wont be supported due to the nature of Python here - not_supported = { - "verifyIncorrectErrorParsing": 1, # we don't deserialize errors in llc - "ResponsesScenarioF400DefaultModel": 1, # don't test this - "ResponsesScenarioF400DefaultNone": 1, # don't test this - "ResponsesScenarioG200DefaultNoModel": 1, # don't test this - } - - # Please add missing features or failing tests here - missing_features_or_bugs = { - 'ConstantsInBody': 1, # https://github.com/Azure/autorest.modelerfour/issues/83 - "ImplicitOptionalBinaryBody": 1, # these are properties on the client, don't know enough info in LLC - "ExplicitRequiredBinaryBody": 1, # these are properties on the client, don't know enough info in LLC - "CustomBaseUri": 1, # don't have enough info on LLC - "CustomBaseUriMoreOptions": 1, - "expectedNoErrors": 1, - "expectedPetSadError": 1, - "expectedPetHungryError": 1, - "intError": 1, - "stringError": 1, - "animalNotFoundError": 1, - "linkNotFoundError": 1, - "putEnumReferencedConstant": 1, # can't do constants on body - "StreamUploadFile": 1, # we don't do formdata bodies anymore - "reservedWordsBodyNamedFiles": 1, # we don't do formdata bodies anymore - "reservedWordsBodyNamedData": 1, # we don't do urlencoded bodies anymore - "UpdatePetWithForm": 1, # we don't do urlencoded bodies anymore - "UrlEncodedDataWithPartialConstantBody": 1, # we don't do urlencoded bodies anymore - } - - 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 - "sendErrorWithParamNameModels": 1, - "putDecimalBigNegativeDecimal": 1, - "verifyHost": 1, - } - 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 - if "Multiapi" in name: - # multiapi is in a separate test folder - missing_features_or_bugs[name] = 1 - if "LLC" in name: - # llc is in a separate test folder - missing_features_or_bugs[name] = 1 - 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) - for s in not_supported.keys(): - print("IGNORING {0}".format(s)) - - if missing_features_or_bugs: - report.update(missing_features_or_bugs) - for s in missing_features_or_bugs.keys(): - print("PENDING {0}".format(s)) - - failed = [k for k, v in report.items() if v == 0] - for s in failed: - 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)) - - if fail_if_missing: - assert 0 == len(failed) diff --git a/test/vanilla/low-level/AcceptanceTests/utils.py b/test/vanilla/low-level/AcceptanceTests/utils.py deleted file mode 100644 index f7f93b1f003..00000000000 --- a/test/vanilla/low-level/AcceptanceTests/utils.py +++ /dev/null @@ -1,38 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- -import json - -try: - JSON_DECODE_ERROR = json.decoder.JSONDecodeError -except: - JSON_DECODE_ERROR = ValueError - - -def dicts_equal(dict_one, dict_two): - assert set(dict_one.keys()) == set(dict_two.keys()) - for key in dict_one.keys(): - assert dict_one[key] == dict_two[key] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/__init__.py deleted file mode 100644 index 39aff0d6920..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AdditionalPropertiesClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AdditionalPropertiesClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_client.py deleted file mode 100644 index 86eabf99cf9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AdditionalPropertiesClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AdditionalPropertiesClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AdditionalPropertiesClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `additionalpropertieslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from additionalpropertieslowlevel.rest import pets - >>> request = pets.build_create_ap_true_request(json=json, content_type=content_type, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AdditionalPropertiesClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_configuration.py deleted file mode 100644 index 79377255703..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AdditionalPropertiesClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AdditionalPropertiesClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AdditionalPropertiesClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "additionalpropertiesclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/__init__.py deleted file mode 100644 index 264cd8df677..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AdditionalPropertiesClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AdditionalPropertiesClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_client.py deleted file mode 100644 index abc8fede910..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AdditionalPropertiesClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AdditionalPropertiesClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AdditionalPropertiesClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `additionalpropertieslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from additionalpropertieslowlevel.rest import pets - >>> request = pets.build_create_ap_true_request(json=json, content_type=content_type, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AdditionalPropertiesClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_configuration.py deleted file mode 100644 index 6957b41d9ba..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AdditionalPropertiesClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AdditionalPropertiesClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AdditionalPropertiesClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "additionalpropertiesclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/pets/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/pets/__init__.py deleted file mode 100644 index 9edd05fa4d2..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/pets/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_create_ap_true_request -from ._request_builders import build_create_cat_ap_true_request -from ._request_builders import build_create_ap_object_request -from ._request_builders import build_create_ap_string_request -from ._request_builders import build_create_ap_in_properties_request -from ._request_builders import build_create_ap_in_properties_with_ap_string_request - -__all__ = [ - "build_create_ap_true_request", - "build_create_cat_ap_true_request", - "build_create_ap_object_request", - "build_create_ap_string_request", - "build_create_ap_in_properties_request", - "build_create_ap_in_properties_with_ap_string_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/pets/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/pets/_request_builders.py deleted file mode 100644 index 2444bcbf062..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/additionalpropertieslowlevel/rest/pets/_request_builders.py +++ /dev/null @@ -1,522 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -@overload -def build_create_ap_true_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": 0, # Required. - "name": "str", # Optional. - "status": bool # Optional. - } - """ - - -@overload -def build_create_ap_true_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_create_ap_true_request(**kwargs: Any) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/additionalProperties/true" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_create_cat_ap_true_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Create a CatAPTrue which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "friendly": bool, # Optional. - "id": 0, # Required. - "name": "str", # Optional. - "status": bool # Optional. - } - """ - - -@overload -def build_create_cat_ap_true_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Create a CatAPTrue which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_create_cat_ap_true_request(**kwargs: Any) -> HttpRequest: - """Create a CatAPTrue which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/additionalProperties/true-subclass" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_create_ap_object_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": 0, # Required. - "name": "str", # Optional. - "status": bool # Optional. - } - """ - - -@overload -def build_create_ap_object_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_create_ap_object_request(**kwargs: Any) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/additionalProperties/type/object" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_create_ap_string_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": 0, # Required. - "name": "str", # Optional. - "status": bool # Optional. - } - """ - - -@overload -def build_create_ap_string_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_create_ap_string_request(**kwargs: Any) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/additionalProperties/type/string" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_create_ap_in_properties_request( - *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": 0, # Required. - "name": "str", # Optional. - "status": bool # Optional. - } - """ - - -@overload -def build_create_ap_in_properties_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_create_ap_in_properties_request(**kwargs: Any) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/additionalProperties/in/properties" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_create_ap_in_properties_with_ap_string_request( - *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "@odata.location": "str", # Required. - "additionalProperties": { - "str": 0.0 # Optional. Dictionary of :code:``. - }, - "id": 0, # Required. - "name": "str", # Optional. - "status": bool # Optional. - } - """ - - -@overload -def build_create_ap_in_properties_with_ap_string_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_create_ap_in_properties_with_ap_string_request(**kwargs: Any) -> HttpRequest: - """Create a Pet which contains more properties than what is defined. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/additionalProperties/in/properties/with/additionalProperties/string" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/setup.py deleted file mode 100644 index 0a5a8ccdcf7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AdditionalPropertiesLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "additionalpropertiesclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AdditionalPropertiesClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/__init__.py deleted file mode 100644 index 11f27f9b05a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AnythingClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AnythingClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_client.py deleted file mode 100644 index 3b58f2cb53e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_client.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AnythingClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AnythingClient: # pylint: disable=client-accepts-api-version-keyword - """Service client for testing basic anything types. Those schemas without types can be anything: - primitive, object, array. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AnythingClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `anythinglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from anythinglowlevel.rest import build_get_object_request - >>> request = build_get_object_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AnythingClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_configuration.py deleted file mode 100644 index a2d66e167b3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AnythingClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AnythingClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AnythingClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "anythingclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/__init__.py deleted file mode 100644 index 475c122ffe6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AnythingClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AnythingClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_client.py deleted file mode 100644 index d29d898a30f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_client.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AnythingClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AnythingClient: # pylint: disable=client-accepts-api-version-keyword - """Service client for testing basic anything types. Those schemas without types can be anything: - primitive, object, array. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AnythingClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `anythinglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from anythinglowlevel.rest import build_get_object_request - >>> request = build_get_object_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AnythingClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_configuration.py deleted file mode 100644 index c2115fb2b46..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AnythingClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AnythingClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AnythingClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "anythingclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/rest/__init__.py deleted file mode 100644 index 8bbae510df2..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/rest/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_object_request -from ._request_builders import build_put_object_request -from ._request_builders import build_get_string_request -from ._request_builders import build_put_string_request -from ._request_builders import build_get_array_request -from ._request_builders import build_put_array_request - -__all__ = [ - "build_get_object_request", - "build_put_object_request", - "build_get_string_request", - "build_put_string_request", - "build_get_array_request", - "build_put_array_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/rest/_request_builders.py deleted file mode 100644 index 884bad222b3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/anythinglowlevel/rest/_request_builders.py +++ /dev/null @@ -1,176 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_object_request(**kwargs: Any) -> HttpRequest: - """Basic get that returns an object as anything. Returns object { 'message': 'An object was - successfully returned' }. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/anything/object" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_object_request(*, json: Any, **kwargs: Any) -> HttpRequest: - """Basic put that puts an object as anything. Pass in {'foo': 'bar'} to get a 200 and anything - else to get an object error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Pass in {'foo': 'bar'} for a 200, anything else for an object error. Required. - :paramtype json: any - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/anything/object" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_string_request(**kwargs: Any) -> HttpRequest: - """Basic get that returns an string as anything. Returns string 'foo'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/anything/string" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_string_request(*, json: Any, **kwargs: Any) -> HttpRequest: - """Basic put that puts an string as anything. Pass in 'anything' to get a 200 and anything else to - get an object error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Pass in 'anything' for a 200, anything else for an object error. Required. - :paramtype json: any - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/anything/string" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_array_request(**kwargs: Any) -> HttpRequest: - """Basic get that returns an array as anything. Returns string ['foo', 'bar']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/anything/array" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_array_request(*, json: Any, **kwargs: Any) -> HttpRequest: - """Basic put that puts an array as anything. Pass in ['foo', 'bar'] to get a 200 and anything else - to get an object error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Pass in ['foo', 'bar'] for a 200, anything else for an object error. Required. - :paramtype json: any - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/anything/array" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/setup.py deleted file mode 100644 index 8bc4978f33e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/AnythingLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "anythingclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AnythingClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Service client for testing basic anything types. Those schemas without types can be anything: primitive, object, array. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/__init__.py deleted file mode 100644 index d9911a116d3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATArrayService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATArrayService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_client.py deleted file mode 100644 index 35c176d06f7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestSwaggerBATArrayServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATArrayService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATArrayServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodyarraylowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodyarraylowlevel.rest import array - >>> request = array.build_get_null_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestSwaggerBATArrayService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_configuration.py deleted file mode 100644 index 65295dce353..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestSwaggerBATArrayServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATArrayService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATArrayServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatarrayservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/__init__.py deleted file mode 100644 index 85f2a2b74ec..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATArrayService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATArrayService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_client.py deleted file mode 100644 index 4fafedd03f1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestSwaggerBATArrayServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATArrayService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATArrayServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodyarraylowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodyarraylowlevel.rest import array - >>> request = array.build_get_null_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestSwaggerBATArrayService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_configuration.py deleted file mode 100644 index 8f8d31c319a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestSwaggerBATArrayServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATArrayService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATArrayServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatarrayservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/array/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/array/__init__.py deleted file mode 100644 index 4a41f8f3fc8..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/array/__init__.py +++ /dev/null @@ -1,149 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_null_request -from ._request_builders import build_get_invalid_request -from ._request_builders import build_get_empty_request -from ._request_builders import build_put_empty_request -from ._request_builders import build_get_boolean_tfft_request -from ._request_builders import build_put_boolean_tfft_request -from ._request_builders import build_get_boolean_invalid_null_request -from ._request_builders import build_get_boolean_invalid_string_request -from ._request_builders import build_get_integer_valid_request -from ._request_builders import build_put_integer_valid_request -from ._request_builders import build_get_int_invalid_null_request -from ._request_builders import build_get_int_invalid_string_request -from ._request_builders import build_get_long_valid_request -from ._request_builders import build_put_long_valid_request -from ._request_builders import build_get_long_invalid_null_request -from ._request_builders import build_get_long_invalid_string_request -from ._request_builders import build_get_float_valid_request -from ._request_builders import build_put_float_valid_request -from ._request_builders import build_get_float_invalid_null_request -from ._request_builders import build_get_float_invalid_string_request -from ._request_builders import build_get_double_valid_request -from ._request_builders import build_put_double_valid_request -from ._request_builders import build_get_double_invalid_null_request -from ._request_builders import build_get_double_invalid_string_request -from ._request_builders import build_get_string_valid_request -from ._request_builders import build_put_string_valid_request -from ._request_builders import build_get_enum_valid_request -from ._request_builders import build_put_enum_valid_request -from ._request_builders import build_get_string_enum_valid_request -from ._request_builders import build_put_string_enum_valid_request -from ._request_builders import build_get_string_with_null_request -from ._request_builders import build_get_string_with_invalid_request -from ._request_builders import build_get_uuid_valid_request -from ._request_builders import build_put_uuid_valid_request -from ._request_builders import build_get_uuid_invalid_chars_request -from ._request_builders import build_get_date_valid_request -from ._request_builders import build_put_date_valid_request -from ._request_builders import build_get_date_invalid_null_request -from ._request_builders import build_get_date_invalid_chars_request -from ._request_builders import build_get_date_time_valid_request -from ._request_builders import build_put_date_time_valid_request -from ._request_builders import build_get_date_time_invalid_null_request -from ._request_builders import build_get_date_time_invalid_chars_request -from ._request_builders import build_get_date_time_rfc1123_valid_request -from ._request_builders import build_put_date_time_rfc1123_valid_request -from ._request_builders import build_get_duration_valid_request -from ._request_builders import build_put_duration_valid_request -from ._request_builders import build_get_byte_valid_request -from ._request_builders import build_put_byte_valid_request -from ._request_builders import build_get_byte_invalid_null_request -from ._request_builders import build_get_base64_url_request -from ._request_builders import build_get_complex_null_request -from ._request_builders import build_get_complex_empty_request -from ._request_builders import build_get_complex_item_null_request -from ._request_builders import build_get_complex_item_empty_request -from ._request_builders import build_get_complex_valid_request -from ._request_builders import build_put_complex_valid_request -from ._request_builders import build_get_array_null_request -from ._request_builders import build_get_array_empty_request -from ._request_builders import build_get_array_item_null_request -from ._request_builders import build_get_array_item_empty_request -from ._request_builders import build_get_array_valid_request -from ._request_builders import build_put_array_valid_request -from ._request_builders import build_get_dictionary_null_request -from ._request_builders import build_get_dictionary_empty_request -from ._request_builders import build_get_dictionary_item_null_request -from ._request_builders import build_get_dictionary_item_empty_request -from ._request_builders import build_get_dictionary_valid_request -from ._request_builders import build_put_dictionary_valid_request - -__all__ = [ - "build_get_null_request", - "build_get_invalid_request", - "build_get_empty_request", - "build_put_empty_request", - "build_get_boolean_tfft_request", - "build_put_boolean_tfft_request", - "build_get_boolean_invalid_null_request", - "build_get_boolean_invalid_string_request", - "build_get_integer_valid_request", - "build_put_integer_valid_request", - "build_get_int_invalid_null_request", - "build_get_int_invalid_string_request", - "build_get_long_valid_request", - "build_put_long_valid_request", - "build_get_long_invalid_null_request", - "build_get_long_invalid_string_request", - "build_get_float_valid_request", - "build_put_float_valid_request", - "build_get_float_invalid_null_request", - "build_get_float_invalid_string_request", - "build_get_double_valid_request", - "build_put_double_valid_request", - "build_get_double_invalid_null_request", - "build_get_double_invalid_string_request", - "build_get_string_valid_request", - "build_put_string_valid_request", - "build_get_enum_valid_request", - "build_put_enum_valid_request", - "build_get_string_enum_valid_request", - "build_put_string_enum_valid_request", - "build_get_string_with_null_request", - "build_get_string_with_invalid_request", - "build_get_uuid_valid_request", - "build_put_uuid_valid_request", - "build_get_uuid_invalid_chars_request", - "build_get_date_valid_request", - "build_put_date_valid_request", - "build_get_date_invalid_null_request", - "build_get_date_invalid_chars_request", - "build_get_date_time_valid_request", - "build_put_date_time_valid_request", - "build_get_date_time_invalid_null_request", - "build_get_date_time_invalid_chars_request", - "build_get_date_time_rfc1123_valid_request", - "build_put_date_time_rfc1123_valid_request", - "build_get_duration_valid_request", - "build_put_duration_valid_request", - "build_get_byte_valid_request", - "build_put_byte_valid_request", - "build_get_byte_invalid_null_request", - "build_get_base64_url_request", - "build_get_complex_null_request", - "build_get_complex_empty_request", - "build_get_complex_item_null_request", - "build_get_complex_item_empty_request", - "build_get_complex_valid_request", - "build_put_complex_valid_request", - "build_get_array_null_request", - "build_get_array_empty_request", - "build_get_array_item_null_request", - "build_get_array_item_empty_request", - "build_get_array_valid_request", - "build_put_array_valid_request", - "build_get_dictionary_null_request", - "build_get_dictionary_empty_request", - "build_get_dictionary_item_null_request", - "build_get_dictionary_item_empty_request", - "build_get_dictionary_valid_request", - "build_put_dictionary_valid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/array/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/array/_request_builders.py deleted file mode 100644 index 8400304fbaa..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/bodyarraylowlevel/rest/array/_request_builders.py +++ /dev/null @@ -1,2791 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -import sys -from typing import Any, Dict, IO, List, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null array value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_request(**kwargs: Any) -> HttpRequest: - """Get invalid array [1, 2, 3. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_empty_request(**kwargs: Any) -> HttpRequest: - """Get empty array value []. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_empty_request(*, json: List[str], content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value empty []. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[str] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - "str" # Optional. - ] - """ - - -@overload -def build_put_empty_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value empty []. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_empty_request(**kwargs: Any) -> HttpRequest: - """Set array value empty []. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[str] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/empty" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_boolean_tfft_request(**kwargs: Any) -> HttpRequest: - """Get boolean array value [true, false, false, true]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/boolean/tfft" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_boolean_tfft_request( - *, json: List[bool], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value empty [true, false, false, true]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[bool] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - bool # Optional. - ] - """ - - -@overload -def build_put_boolean_tfft_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value empty [true, false, false, true]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_boolean_tfft_request(**kwargs: Any) -> HttpRequest: - """Set array value empty [true, false, false, true]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[bool] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/boolean/tfft" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_boolean_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get boolean array value [true, null, false]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/boolean/true.null.false" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_boolean_invalid_string_request(**kwargs: Any) -> HttpRequest: - """Get boolean array value [true, 'boolean', false]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/boolean/true.boolean.false" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_integer_valid_request(**kwargs: Any) -> HttpRequest: - """Get integer array value [1, -1, 3, 300]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/integer/1.-1.3.300" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_integer_valid_request( - *, json: List[int], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value empty [1, -1, 3, 300]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[int] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - 0 # Optional. - ] - """ - - -@overload -def build_put_integer_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value empty [1, -1, 3, 300]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_integer_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value empty [1, -1, 3, 300]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[int] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/integer/1.-1.3.300" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_int_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get integer array value [1, null, 0]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/integer/1.null.zero" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_int_invalid_string_request(**kwargs: Any) -> HttpRequest: - """Get integer array value [1, 'integer', 0]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/integer/1.integer.0" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_long_valid_request(**kwargs: Any) -> HttpRequest: - """Get integer array value [1, -1, 3, 300]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/long/1.-1.3.300" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_long_valid_request(*, json: List[int], content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value empty [1, -1, 3, 300]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[int] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - 0 # Optional. - ] - """ - - -@overload -def build_put_long_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value empty [1, -1, 3, 300]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_long_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value empty [1, -1, 3, 300]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[int] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/long/1.-1.3.300" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_long_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get long array value [1, null, 0]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/long/1.null.zero" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_long_invalid_string_request(**kwargs: Any) -> HttpRequest: - """Get long array value [1, 'integer', 0]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/long/1.integer.0" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_float_valid_request(**kwargs: Any) -> HttpRequest: - """Get float array value [0, -0.01, 1.2e20]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/float/0--0.01-1.2e20" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_float_valid_request( - *, json: List[float], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value [0, -0.01, 1.2e20]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[float] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - 0.0 # Optional. - ] - """ - - -@overload -def build_put_float_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value [0, -0.01, 1.2e20]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_float_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value [0, -0.01, 1.2e20]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[float] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/float/0--0.01-1.2e20" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_float_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get float array value [0.0, null, -1.2e20]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/float/0.0-null-1.2e20" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_float_invalid_string_request(**kwargs: Any) -> HttpRequest: - """Get boolean array value [1.0, 'number', 0.0]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/float/1.number.0" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_double_valid_request(**kwargs: Any) -> HttpRequest: - """Get float array value [0, -0.01, 1.2e20]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/double/0--0.01-1.2e20" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_double_valid_request( - *, json: List[float], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value [0, -0.01, 1.2e20]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[float] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - 0.0 # Optional. - ] - """ - - -@overload -def build_put_double_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value [0, -0.01, 1.2e20]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_double_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value [0, -0.01, 1.2e20]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[float] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/double/0--0.01-1.2e20" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_double_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get float array value [0.0, null, -1.2e20]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/double/0.0-null-1.2e20" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_double_invalid_string_request(**kwargs: Any) -> HttpRequest: - """Get boolean array value [1.0, 'number', 0.0]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/double/1.number.0" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_string_valid_request(**kwargs: Any) -> HttpRequest: - """Get string array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/string/foo1.foo2.foo3" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_string_valid_request( - *, json: List[str], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[str] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - "str" # Optional. - ] - """ - - -@overload -def build_put_string_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_string_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[str] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/string/foo1.foo2.foo3" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_enum_valid_request(**kwargs: Any) -> HttpRequest: - """Get enum array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/enum/foo1.foo2.foo3" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_enum_valid_request(*, json: List[str], content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[str] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - "str" # Optional. - ] - """ - - -@overload -def build_put_enum_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_enum_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[str] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/enum/foo1.foo2.foo3" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_string_enum_valid_request(**kwargs: Any) -> HttpRequest: - """Get enum array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/string-enum/foo1.foo2.foo3" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_string_enum_valid_request( - *, json: List[str], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[str] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - "str" # Optional. - ] - """ - - -@overload -def build_put_string_enum_valid_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_string_enum_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value ['foo1', 'foo2', 'foo3']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[str] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/string-enum/foo1.foo2.foo3" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_string_with_null_request(**kwargs: Any) -> HttpRequest: - """Get string array value ['foo', null, 'foo2']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/string/foo.null.foo2" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_string_with_invalid_request(**kwargs: Any) -> HttpRequest: - """Get string array value ['foo', 123, 'foo2']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/string/foo.123.foo2" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_uuid_valid_request(**kwargs: Any) -> HttpRequest: - """Get uuid array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', - 'd1399005-30f7-40d6-8da6-dd7c89ad34db', 'f42f6aa1-a5bc-4ddf-907e-5f915de43205']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/uuid/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_uuid_valid_request(*, json: List[str], content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', - 'd1399005-30f7-40d6-8da6-dd7c89ad34db', 'f42f6aa1-a5bc-4ddf-907e-5f915de43205']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[str] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - "str" # Optional. - ] - """ - - -@overload -def build_put_uuid_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', - 'd1399005-30f7-40d6-8da6-dd7c89ad34db', 'f42f6aa1-a5bc-4ddf-907e-5f915de43205']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_uuid_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', - 'd1399005-30f7-40d6-8da6-dd7c89ad34db', 'f42f6aa1-a5bc-4ddf-907e-5f915de43205']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[str] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/uuid/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_uuid_invalid_chars_request(**kwargs: Any) -> HttpRequest: - """Get uuid array value ['6dcc7237-45fe-45c4-8a6b-3a8a3f625652', 'foo']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/uuid/invalidchars" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_date_valid_request(**kwargs: Any) -> HttpRequest: - """Get integer array value ['2000-12-01', '1980-01-02', '1492-10-12']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/date/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_date_valid_request( - *, json: List[datetime.date], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value ['2000-12-01', '1980-01-02', '1492-10-12']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[~datetime.date] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - "2020-02-20" # Optional. - ] - """ - - -@overload -def build_put_date_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value ['2000-12-01', '1980-01-02', '1492-10-12']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_date_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value ['2000-12-01', '1980-01-02', '1492-10-12']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[~datetime.date] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/date/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_date_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get date array value ['2012-01-01', null, '1776-07-04']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/date/invalidnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_date_invalid_chars_request(**kwargs: Any) -> HttpRequest: - """Get date array value ['2011-03-22', 'date']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/date/invalidchars" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_date_time_valid_request(**kwargs: Any) -> HttpRequest: - """Get date-time array value ['2000-12-01t00:00:01z', '1980-01-02T00:11:35+01:00', - '1492-10-12T10:15:01-08:00']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/date-time/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_date_time_valid_request( - *, json: List[datetime.datetime], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value ['2000-12-01t00:00:01z', '1980-01-02T00:11:35+01:00', - '1492-10-12T10:15:01-08:00']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[~datetime.datetime] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - "2020-02-20 00:00:00" # Optional. - ] - """ - - -@overload -def build_put_date_time_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value ['2000-12-01t00:00:01z', '1980-01-02T00:11:35+01:00', - '1492-10-12T10:15:01-08:00']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_date_time_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value ['2000-12-01t00:00:01z', '1980-01-02T00:11:35+01:00', - '1492-10-12T10:15:01-08:00']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[~datetime.datetime] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/date-time/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_date_time_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get date array value ['2000-12-01t00:00:01z', null]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/date-time/invalidnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_date_time_invalid_chars_request(**kwargs: Any) -> HttpRequest: - """Get date array value ['2000-12-01t00:00:01z', 'date-time']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/date-time/invalidchars" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_date_time_rfc1123_valid_request(**kwargs: Any) -> HttpRequest: - """Get date-time array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', - 'Wed, 12 Oct 1492 10:15:01 GMT']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/date-time-rfc1123/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_date_time_rfc1123_valid_request( - *, json: List[datetime.datetime], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, 12 - Oct 1492 10:15:01 GMT']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[~datetime.datetime] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - "2020-02-20 00:00:00" # Optional. - ] - """ - - -@overload -def build_put_date_time_rfc1123_valid_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, 12 - Oct 1492 10:15:01 GMT']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_date_time_rfc1123_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value ['Fri, 01 Dec 2000 00:00:01 GMT', 'Wed, 02 Jan 1980 00:11:35 GMT', 'Wed, 12 - Oct 1492 10:15:01 GMT']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[~datetime.datetime] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/date-time-rfc1123/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_duration_valid_request(**kwargs: Any) -> HttpRequest: - """Get duration array value ['P123DT22H14M12.011S', 'P5DT1H0M0S']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/duration/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_duration_valid_request( - *, json: List[datetime.timedelta], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set array value ['P123DT22H14M12.011S', 'P5DT1H0M0S']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[~datetime.timedelta] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - "1 day, 0:00:00" # Optional. - ] - """ - - -@overload -def build_put_duration_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set array value ['P123DT22H14M12.011S', 'P5DT1H0M0S']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_duration_valid_request(**kwargs: Any) -> HttpRequest: - """Set array value ['P123DT22H14M12.011S', 'P5DT1H0M0S']. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[~datetime.timedelta] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/duration/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_byte_valid_request(**kwargs: Any) -> HttpRequest: - """Get byte array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, 43)] with each item encoded - in base64. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/byte/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_byte_valid_request( - *, json: List[bytes], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put the array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, 43)] with each - elementencoded in base 64. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - bytes("bytes", encoding="utf-8") # Optional. - ] - """ - - -@overload -def build_put_byte_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put the array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, 43)] with each - elementencoded in base 64. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_byte_valid_request(**kwargs: Any) -> HttpRequest: - """Put the array value [hex(FF FF FF FA), hex(01 02 03), hex (25, 29, 43)] with each - elementencoded in base 64. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[bytes] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/byte/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_byte_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get byte array value [hex(AB, AC, AD), null] with the first item base64 encoded. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/byte/invalidnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_base64_url_request(**kwargs: Any) -> HttpRequest: - """Get array value ['a string that gets encoded with base64url', 'test string' 'Lorem ipsum'] with - the items base64url encoded. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/prim/base64url/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_complex_null_request(**kwargs: Any) -> HttpRequest: - """Get array of complex type null value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/complex/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_complex_empty_request(**kwargs: Any) -> HttpRequest: - """Get empty array of complex type []. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/complex/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_complex_item_null_request(**kwargs: Any) -> HttpRequest: - """Get array of complex type with null item [{'integer': 1 'string': '2'}, null, {'integer': 5, - 'string': '6'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/complex/itemnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_complex_item_empty_request(**kwargs: Any) -> HttpRequest: - """Get array of complex type with empty item [{'integer': 1 'string': '2'}, {}, {'integer': 5, - 'string': '6'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/complex/itemempty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_complex_valid_request(**kwargs: Any) -> HttpRequest: - """Get array of complex type with [{'integer': 1 'string': '2'}, {'integer': 3, 'string': '4'}, - {'integer': 5, 'string': '6'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/complex/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_complex_valid_request( - *, json: List[JSON], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put an array of complex type with values [{'integer': 1 'string': '2'}, {'integer': 3, - 'string': '4'}, {'integer': 5, 'string': '6'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[JSON] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - { - "integer": 0, # Optional. - "string": "str" # Optional. - } - ] - """ - - -@overload -def build_put_complex_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put an array of complex type with values [{'integer': 1 'string': '2'}, {'integer': 3, - 'string': '4'}, {'integer': 5, 'string': '6'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_complex_valid_request(**kwargs: Any) -> HttpRequest: - """Put an array of complex type with values [{'integer': 1 'string': '2'}, {'integer': 3, - 'string': '4'}, {'integer': 5, 'string': '6'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[JSON] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/complex/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_array_null_request(**kwargs: Any) -> HttpRequest: - """Get a null array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/array/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_array_empty_request(**kwargs: Any) -> HttpRequest: - """Get an empty array []. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/array/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_array_item_null_request(**kwargs: Any) -> HttpRequest: - """Get an array of array of strings [['1', '2', '3'], null, ['7', '8', '9']]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/array/itemnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_array_item_empty_request(**kwargs: Any) -> HttpRequest: - """Get an array of array of strings [['1', '2', '3'], [], ['7', '8', '9']]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/array/itemempty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_array_valid_request(**kwargs: Any) -> HttpRequest: - """Get an array of array of strings [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/array/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_array_valid_request( - *, json: List[List[str]], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put An array of array of strings [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[list[str]] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - [ - "str" # Optional. - ] - ] - """ - - -@overload -def build_put_array_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put An array of array of strings [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_array_valid_request(**kwargs: Any) -> HttpRequest: - """Put An array of array of strings [['1', '2', '3'], ['4', '5', '6'], ['7', '8', '9']]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[list[str]] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/array/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_dictionary_null_request(**kwargs: Any) -> HttpRequest: - """Get an array of Dictionaries with value null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/dictionary/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_dictionary_empty_request(**kwargs: Any) -> HttpRequest: - """Get an array of Dictionaries of type with value []. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/dictionary/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_dictionary_item_null_request(**kwargs: Any) -> HttpRequest: - """Get an array of Dictionaries of type with value [{'1': 'one', '2': 'two', '3': - 'three'}, null, {'7': 'seven', '8': 'eight', '9': 'nine'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/dictionary/itemnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_dictionary_item_empty_request(**kwargs: Any) -> HttpRequest: - """Get an array of Dictionaries of type with value [{'1': 'one', '2': 'two', '3': - 'three'}, {}, {'7': 'seven', '8': 'eight', '9': 'nine'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/dictionary/itemempty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_dictionary_valid_request(**kwargs: Any) -> HttpRequest: - """Get an array of Dictionaries of type with value [{'1': 'one', '2': 'two', '3': - 'three'}, {'4': 'four', '5': 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/dictionary/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_dictionary_valid_request( - *, json: List[Dict[str, str]], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Get an array of Dictionaries of type with value [{'1': 'one', '2': 'two', '3': - 'three'}, {'4': 'four', '5': 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[dict[str, str]] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - { - "str": "str" # Optional. - } - ] - """ - - -@overload -def build_put_dictionary_valid_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Get an array of Dictionaries of type with value [{'1': 'one', '2': 'two', '3': - 'three'}, {'4': 'four', '5': 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_dictionary_valid_request(**kwargs: Any) -> HttpRequest: - """Get an array of Dictionaries of type with value [{'1': 'one', '2': 'two', '3': - 'three'}, {'4': 'four', '5': 'five', '6': 'six'}, {'7': 'seven', '8': 'eight', '9': 'nine'}]. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[dict[str, str]] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/array/dictionary/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/setup.py deleted file mode 100644 index d5b3f6c87da..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyArrayLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestswaggerbatarrayservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestSwaggerBATArrayService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest Swagger BAT. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/__init__.py deleted file mode 100644 index a874bbe1b70..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import BinaryWithContentTypeApplicationJson -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["BinaryWithContentTypeApplicationJson"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_client.py deleted file mode 100644 index 09ee933aae2..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import BinaryWithContentTypeApplicationJsonConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class BinaryWithContentTypeApplicationJson: # pylint: disable=client-accepts-api-version-keyword - """Sample for file with json and binary content type. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = BinaryWithContentTypeApplicationJsonConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodybinarylowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodybinarylowlevel.rest import upload - >>> request = upload.build_file_request(content=content, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> BinaryWithContentTypeApplicationJson - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_configuration.py deleted file mode 100644 index 72d1f0304aa..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class BinaryWithContentTypeApplicationJsonConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for BinaryWithContentTypeApplicationJson. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(BinaryWithContentTypeApplicationJsonConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "binarywithcontenttypeapplicationjson/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/__init__.py deleted file mode 100644 index 6a3a6091304..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import BinaryWithContentTypeApplicationJson - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["BinaryWithContentTypeApplicationJson"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_client.py deleted file mode 100644 index 6b3d97bf633..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import BinaryWithContentTypeApplicationJsonConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class BinaryWithContentTypeApplicationJson: # pylint: disable=client-accepts-api-version-keyword - """Sample for file with json and binary content type. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = BinaryWithContentTypeApplicationJsonConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodybinarylowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodybinarylowlevel.rest import upload - >>> request = upload.build_file_request(content=content, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "BinaryWithContentTypeApplicationJson": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_configuration.py deleted file mode 100644 index b3128d7c18b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class BinaryWithContentTypeApplicationJsonConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for BinaryWithContentTypeApplicationJson. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(BinaryWithContentTypeApplicationJsonConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "binarywithcontenttypeapplicationjson/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/upload/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/upload/__init__.py deleted file mode 100644 index 497aaf1b829..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/upload/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_file_request -from ._request_builders import build_binary_request - -__all__ = [ - "build_file_request", - "build_binary_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/upload/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/upload/_request_builders.py deleted file mode 100644 index b73dc5b1d7e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/bodybinarylowlevel/rest/upload/_request_builders.py +++ /dev/null @@ -1,70 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, IO, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_file_request(*, content: IO, **kwargs: Any) -> HttpRequest: - """Uploading json file. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: JSON file with payload { "more": "cowbell" }. Required. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/binary/file" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, content=content, **kwargs) - - -def build_binary_request(*, content: IO, **kwargs: Any) -> HttpRequest: - """Uploading binary file. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Non-empty binary file. Required. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/binary/octet" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/setup.py deleted file mode 100644 index deb1dfc0e3c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBinaryLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "binarywithcontenttypeapplicationjson" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="BinaryWithContentTypeApplicationJson", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Sample for file with json and binary content type. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/__init__.py deleted file mode 100644 index 351d58101ae..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestBoolTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestBoolTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_client.py deleted file mode 100644 index ef92aab6137..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestBoolTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestBoolTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestBoolTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodybooleanlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodybooleanlowlevel.rest import bool - >>> request = bool.build_get_true_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestBoolTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_configuration.py deleted file mode 100644 index 7b8d0b2d571..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestBoolTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestBoolTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestBoolTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestbooltestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/__init__.py deleted file mode 100644 index 5483ed83224..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestBoolTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestBoolTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_client.py deleted file mode 100644 index 33f72f97727..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestBoolTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestBoolTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestBoolTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodybooleanlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodybooleanlowlevel.rest import bool - >>> request = bool.build_get_true_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestBoolTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_configuration.py deleted file mode 100644 index fd4d1a40235..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestBoolTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestBoolTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestBoolTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestbooltestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/bool/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/bool/__init__.py deleted file mode 100644 index ef53078c983..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/bool/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_true_request -from ._request_builders import build_put_true_request -from ._request_builders import build_get_false_request -from ._request_builders import build_put_false_request -from ._request_builders import build_get_null_request -from ._request_builders import build_get_invalid_request - -__all__ = [ - "build_get_true_request", - "build_put_true_request", - "build_get_false_request", - "build_put_false_request", - "build_get_null_request", - "build_get_invalid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/bool/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/bool/_request_builders.py deleted file mode 100644 index f2623176969..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/bodybooleanlowlevel/rest/bool/_request_builders.py +++ /dev/null @@ -1,180 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_true_request(**kwargs: Any) -> HttpRequest: - """Get true Boolean value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/bool/true" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_true_request(**kwargs: Any) -> HttpRequest: - """Set Boolean value true. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Default value is True. Note that overriding this default value may result in - unsupported behavior. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - json = kwargs.pop("json", True) # type: bool - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/bool/true" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_false_request(**kwargs: Any) -> HttpRequest: - """Get false Boolean value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/bool/false" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_false_request(**kwargs: Any) -> HttpRequest: - """Set Boolean value false. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. Default value is False. Note that overriding this default value may - result in unsupported behavior. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - json = kwargs.pop("json", False) # type: bool - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/bool/false" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null Boolean value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/bool/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_request(**kwargs: Any) -> HttpRequest: - """Get invalid Boolean value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/bool/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/setup.py deleted file mode 100644 index f6b47d728f4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyBooleanLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestbooltestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestBoolTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/__init__.py deleted file mode 100644 index edfabd3a473..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATByteService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATByteService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_client.py deleted file mode 100644 index ee8ab676bf0..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestSwaggerBATByteServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATByteService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATByteServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodybytelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodybytelowlevel.rest import byte - >>> request = byte.build_get_null_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestSwaggerBATByteService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_configuration.py deleted file mode 100644 index 94dface9e51..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestSwaggerBATByteServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATByteService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATByteServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatbyteservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/__init__.py deleted file mode 100644 index 7a2433556a7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATByteService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATByteService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_client.py deleted file mode 100644 index 704f146c4f6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestSwaggerBATByteServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATByteService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATByteServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodybytelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodybytelowlevel.rest import byte - >>> request = byte.build_get_null_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestSwaggerBATByteService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_configuration.py deleted file mode 100644 index 5d92724f30f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestSwaggerBATByteServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATByteService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATByteServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatbyteservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/byte/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/byte/__init__.py deleted file mode 100644 index e3c5ab02796..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/byte/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_null_request -from ._request_builders import build_get_empty_request -from ._request_builders import build_get_non_ascii_request -from ._request_builders import build_put_non_ascii_request -from ._request_builders import build_get_invalid_request - -__all__ = [ - "build_get_null_request", - "build_get_empty_request", - "build_get_non_ascii_request", - "build_put_non_ascii_request", - "build_get_invalid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/byte/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/byte/_request_builders.py deleted file mode 100644 index b1af6d7a6cc..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/bodybytelowlevel/rest/byte/_request_builders.py +++ /dev/null @@ -1,147 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null byte value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/byte/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_empty_request(**kwargs: Any) -> HttpRequest: - """Get empty byte value ''. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/byte/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_non_ascii_request(**kwargs: Any) -> HttpRequest: - """Get non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/byte/nonAscii" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_non_ascii_request(*, json: bytes, **kwargs: Any) -> HttpRequest: - """Put non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Base64-encoded non-ascii byte string hex(FF FE FD FC FB FA F9 F8 F7 F6). - Required. - :paramtype json: bytes - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/byte/nonAscii" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_invalid_request(**kwargs: Any) -> HttpRequest: - """Get invalid byte value ':::SWAGGER::::'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/byte/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/setup.py deleted file mode 100644 index 3e221c01e97..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyByteLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestswaggerbatbyteservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestSwaggerBATByteService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest Swagger BAT. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/__init__.py deleted file mode 100644 index 2edcaf40ebe..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestComplexTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestComplexTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_client.py deleted file mode 100644 index 5fe39643261..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_client.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestComplexTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestComplexTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - :keyword api_version: Api Version. Default value is "2016-02-29". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestComplexTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodycomplexlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodycomplexlowlevel.rest import basic - >>> request = basic.build_get_valid_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestComplexTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_configuration.py deleted file mode 100644 index 0f9535aa04d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_configuration.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestComplexTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestComplexTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :keyword api_version: Api Version. Default value is "2016-02-29". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestComplexTestServiceConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2016-02-29") # type: str - - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "autorestcomplextestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/__init__.py deleted file mode 100644 index 3756364af6e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestComplexTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestComplexTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_client.py deleted file mode 100644 index f758debe761..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestComplexTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestComplexTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - :keyword api_version: Api Version. Default value is "2016-02-29". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestComplexTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodycomplexlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodycomplexlowlevel.rest import basic - >>> request = basic.build_get_valid_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestComplexTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_configuration.py deleted file mode 100644 index b16d2bb13a8..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_configuration.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestComplexTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestComplexTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :keyword api_version: Api Version. Default value is "2016-02-29". Note that overriding this - default value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestComplexTestServiceConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "2016-02-29") # type: str - - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "autorestcomplextestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/array/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/array/__init__.py deleted file mode 100644 index 9aafa008cb7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/array/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_valid_request -from ._request_builders import build_put_valid_request -from ._request_builders import build_get_empty_request -from ._request_builders import build_put_empty_request -from ._request_builders import build_get_not_provided_request - -__all__ = [ - "build_get_valid_request", - "build_put_valid_request", - "build_get_empty_request", - "build_put_empty_request", - "build_get_not_provided_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/array/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/array/_request_builders.py deleted file mode 100644 index fccc1658f22..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/array/_request_builders.py +++ /dev/null @@ -1,263 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_valid_request(**kwargs: Any) -> HttpRequest: - """Get complex types with array property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/array/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_valid_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with array property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put an array with 4 items: "1, 2, 3, 4", "", null, "&S#$(*Y", "The quick - brown fox jumps over the lazy dog". Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "array": [ - "str" # Optional. - ] - } - """ - - -@overload -def build_put_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with array property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put an array with 4 items: "1, 2, 3, 4", "", null, "&S#$(*Y", "The - quick brown fox jumps over the lazy dog". Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_valid_request(**kwargs: Any) -> HttpRequest: - """Put complex types with array property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put an array with 4 items: "1, 2, 3, 4", "", null, "&S#$(*Y", "The quick - brown fox jumps over the lazy dog". Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/array/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_empty_request(**kwargs: Any) -> HttpRequest: - """Get complex types with array property which is empty. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/array/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_empty_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with array property which is empty. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put an empty array. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "array": [ - "str" # Optional. - ] - } - """ - - -@overload -def build_put_empty_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with array property which is empty. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put an empty array. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_empty_request(**kwargs: Any) -> HttpRequest: - """Put complex types with array property which is empty. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put an empty array. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/array/empty" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_not_provided_request(**kwargs: Any) -> HttpRequest: - """Get complex types with array property while server doesn't provide a response payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/array/notprovided" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/basic/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/basic/__init__.py deleted file mode 100644 index 9b5f914f0e9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/basic/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_valid_request -from ._request_builders import build_put_valid_request -from ._request_builders import build_get_invalid_request -from ._request_builders import build_get_empty_request -from ._request_builders import build_get_null_request -from ._request_builders import build_get_not_provided_request - -__all__ = [ - "build_get_valid_request", - "build_put_valid_request", - "build_get_invalid_request", - "build_get_empty_request", - "build_get_null_request", - "build_get_not_provided_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/basic/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/basic/_request_builders.py deleted file mode 100644 index 00cdf82d48b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/basic/_request_builders.py +++ /dev/null @@ -1,237 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_valid_request(**kwargs: Any) -> HttpRequest: - """Get complex type {id: 2, name: 'abc', color: 'YELLOW'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/basic/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_valid_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Please put {id: 2, name: 'abc', color: 'Magenta'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put {id: 2, name: 'abc', color: 'Magenta'}. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "color": "str", # Optional. Known values are: "cyan", "Magenta", "YELLOW", - and "blacK". - "id": 0, # Optional. Basic Id. - "name": "str" # Optional. Name property with a very long description that - does not fit on a single line and a line break. - } - """ - - -@overload -def build_put_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Please put {id: 2, name: 'abc', color: 'Magenta'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put {id: 2, name: 'abc', color: 'Magenta'}. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_valid_request(**kwargs: Any) -> HttpRequest: - """Please put {id: 2, name: 'abc', color: 'Magenta'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put {id: 2, name: 'abc', color: 'Magenta'}. Is either a model type or a - IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("api-version", "2016-02-29")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/basic/valid" - - # Construct parameters - _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_invalid_request(**kwargs: Any) -> HttpRequest: - """Get a basic complex type that is invalid for the local strong type. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/basic/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_empty_request(**kwargs: Any) -> HttpRequest: - """Get a basic complex type that is empty. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/basic/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get a basic complex type whose properties are null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/basic/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_not_provided_request(**kwargs: Any) -> HttpRequest: - """Get a basic complex type while the server doesn't provide a response payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/basic/notprovided" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/dictionary/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/dictionary/__init__.py deleted file mode 100644 index 643312c6e30..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/dictionary/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_valid_request -from ._request_builders import build_put_valid_request -from ._request_builders import build_get_empty_request -from ._request_builders import build_put_empty_request -from ._request_builders import build_get_null_request -from ._request_builders import build_get_not_provided_request - -__all__ = [ - "build_get_valid_request", - "build_put_valid_request", - "build_get_empty_request", - "build_put_empty_request", - "build_get_null_request", - "build_get_not_provided_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/dictionary/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/dictionary/_request_builders.py deleted file mode 100644 index 311e7d90b2c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/dictionary/_request_builders.py +++ /dev/null @@ -1,289 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_valid_request(**kwargs: Any) -> HttpRequest: - """Get complex types with dictionary property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/dictionary/typed/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_valid_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with dictionary property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put a dictionary with 5 key-value pairs: "txt":"notepad", - "bmp":"mspaint", "xls":"excel", "exe":"", "":null. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "defaultProgram": { - "str": "str" # Optional. Dictionary of :code:``. - } - } - """ - - -@overload -def build_put_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with dictionary property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put a dictionary with 5 key-value pairs: "txt":"notepad", - "bmp":"mspaint", "xls":"excel", "exe":"", "":null. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_valid_request(**kwargs: Any) -> HttpRequest: - """Put complex types with dictionary property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put a dictionary with 5 key-value pairs: "txt":"notepad", - "bmp":"mspaint", "xls":"excel", "exe":"", "":null. Is either a model type or a IO type. - Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/dictionary/typed/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_empty_request(**kwargs: Any) -> HttpRequest: - """Get complex types with dictionary property which is empty. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/dictionary/typed/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_empty_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with dictionary property which is empty. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put an empty dictionary. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "defaultProgram": { - "str": "str" # Optional. Dictionary of :code:``. - } - } - """ - - -@overload -def build_put_empty_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with dictionary property which is empty. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put an empty dictionary. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_empty_request(**kwargs: Any) -> HttpRequest: - """Put complex types with dictionary property which is empty. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put an empty dictionary. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/dictionary/typed/empty" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get complex types with dictionary property which is null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/dictionary/typed/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_not_provided_request(**kwargs: Any) -> HttpRequest: - """Get complex types with dictionary property while server doesn't provide a response payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/dictionary/typed/notprovided" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/flattencomplex/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/flattencomplex/__init__.py deleted file mode 100644 index 2d06b2ea023..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/flattencomplex/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_valid_request - -__all__ = [ - "build_get_valid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/flattencomplex/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/flattencomplex/_request_builders.py deleted file mode 100644 index b22419d74a7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/flattencomplex/_request_builders.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_valid_request(**kwargs: Any) -> HttpRequest: - """get_valid. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/flatten/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/inheritance/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/inheritance/__init__.py deleted file mode 100644 index a0483f76f03..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/inheritance/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_valid_request -from ._request_builders import build_put_valid_request - -__all__ = [ - "build_get_valid_request", - "build_put_valid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/inheritance/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/inheritance/_request_builders.py deleted file mode 100644 index 7f50a9060c1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/inheritance/_request_builders.py +++ /dev/null @@ -1,144 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_valid_request(**kwargs: Any) -> HttpRequest: - """Get complex types that extend others. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/inheritance/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_valid_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types that extend others. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put a siamese with id=2, name="Siameee", color=green, breed=persion, - which hates 2 dogs, the 1st one named "Potato" with id=1 and food="tomato", and the 2nd one - named "Tomato" with id=-1 and food="french fries". Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "breed": "str", # Optional. - "color": "str", # Optional. - "hates": [ - { - "food": "str", # Optional. - "id": 0, # Optional. - "name": "str" # Optional. - } - ], - "id": 0, # Optional. - "name": "str" # Optional. - } - """ - - -@overload -def build_put_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types that extend others. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put a siamese with id=2, name="Siameee", color=green, breed=persion, - which hates 2 dogs, the 1st one named "Potato" with id=1 and food="tomato", and the 2nd one - named "Tomato" with id=-1 and food="french fries". Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_valid_request(**kwargs: Any) -> HttpRequest: - """Put complex types that extend others. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put a siamese with id=2, name="Siameee", color=green, breed=persion, - which hates 2 dogs, the 1st one named "Potato" with id=1 and food="tomato", and the 2nd one - named "Tomato" with id=-1 and food="french fries". Is either a model type or a IO type. - Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/inheritance/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphicrecursive/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphicrecursive/__init__.py deleted file mode 100644 index a0483f76f03..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphicrecursive/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_valid_request -from ._request_builders import build_put_valid_request - -__all__ = [ - "build_get_valid_request", - "build_put_valid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphicrecursive/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphicrecursive/_request_builders.py deleted file mode 100644 index 1ff9a93a548..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphicrecursive/_request_builders.py +++ /dev/null @@ -1,337 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_valid_request(**kwargs: Any) -> HttpRequest: - """Get complex types that are polymorphic and have recursive references. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/polymorphicrecursive/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_valid_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types that are polymorphic and have recursive references. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put a salmon that looks like this: - { - "fishtype": "salmon", - "species": "king", - "length": 1, - "age": 1, - "location": "alaska", - "iswild": true, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20, - "age": 6, - "siblings": [ - { - "fishtype": "salmon", - "species": "coho", - "length": 2, - "age": 2, - "location": "atlantic", - "iswild": true, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20, - "age": 6 - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10, - "age": 105 - } - ] - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10, - "age": 105 - } - ] - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10, - "age": 105 - } - ] - }. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "fishtype": - - # JSON input template for discriminator value "smart_salmon": - fish = { - "college_degree": "str", # Optional. - "fishtype": "smart_salmon", - "iswild": bool, # Optional. - "length": 0.0, # Required. - "location": "str", # Optional. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template for discriminator value "cookiecuttershark": - fish = { - "age": 0, # Optional. - "birthday": "2020-02-20 00:00:00", # Required. - "fishtype": "cookiecuttershark", - "length": 0.0, # Required. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template for discriminator value "goblin": - fish = { - "age": 0, # Optional. - "birthday": "2020-02-20 00:00:00", # Required. - "color": "gray", # Optional. Default value is "gray". Colors possible. Known - values are: "pink", "gray", "brown", "RED", and "red". - "fishtype": "goblin", - "jawsize": 0, # Optional. - "length": 0.0, # Required. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template for discriminator value "sawshark": - fish = { - "age": 0, # Optional. - "birthday": "2020-02-20 00:00:00", # Required. - "fishtype": "sawshark", - "length": 0.0, # Required. - "picture": bytes("bytes", encoding="utf-8"), # Optional. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template you can fill out and use as your body input. - json = fish - """ - - -@overload -def build_put_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types that are polymorphic and have recursive references. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put a salmon that looks like this: - { - "fishtype": "salmon", - "species": "king", - "length": 1, - "age": 1, - "location": "alaska", - "iswild": true, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20, - "age": 6, - "siblings": [ - { - "fishtype": "salmon", - "species": "coho", - "length": 2, - "age": 2, - "location": "atlantic", - "iswild": true, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20, - "age": 6 - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10, - "age": 105 - } - ] - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10, - "age": 105 - } - ] - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10, - "age": 105 - } - ] - }. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_valid_request(**kwargs: Any) -> HttpRequest: - """Put complex types that are polymorphic and have recursive references. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put a salmon that looks like this: - { - "fishtype": "salmon", - "species": "king", - "length": 1, - "age": 1, - "location": "alaska", - "iswild": true, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20, - "age": 6, - "siblings": [ - { - "fishtype": "salmon", - "species": "coho", - "length": 2, - "age": 2, - "location": "atlantic", - "iswild": true, - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "length": 20, - "age": 6 - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10, - "age": 105 - } - ] - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10, - "age": 105 - } - ] - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "length": 10, - "age": 105 - } - ] - }. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/polymorphicrecursive/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphism/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphism/__init__.py deleted file mode 100644 index a92b467a018..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphism/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_valid_request -from ._request_builders import build_put_valid_request -from ._request_builders import build_get_dot_syntax_request -from ._request_builders import build_get_composed_with_discriminator_request -from ._request_builders import build_get_composed_without_discriminator_request -from ._request_builders import build_get_complicated_request -from ._request_builders import build_put_complicated_request -from ._request_builders import build_put_missing_discriminator_request -from ._request_builders import build_put_valid_missing_required_request - -__all__ = [ - "build_get_valid_request", - "build_put_valid_request", - "build_get_dot_syntax_request", - "build_get_composed_with_discriminator_request", - "build_get_composed_without_discriminator_request", - "build_get_complicated_request", - "build_put_complicated_request", - "build_put_missing_discriminator_request", - "build_put_valid_missing_required_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphism/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphism/_request_builders.py deleted file mode 100644 index 50a817cd96e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/polymorphism/_request_builders.py +++ /dev/null @@ -1,793 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_valid_request(**kwargs: Any) -> HttpRequest: - """Get complex types that are polymorphic. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/polymorphism/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_valid_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types that are polymorphic. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put a salmon that looks like this: - { - 'fishtype':'Salmon', - 'location':'alaska', - 'iswild':true, - 'species':'king', - 'length':1.0, - 'siblings':[ - { - 'fishtype':'Shark', - 'age':6, - 'birthday': '2012-01-05T01:00:00Z', - 'length':20.0, - 'species':'predator', - }, - { - 'fishtype':'Sawshark', - 'age':105, - 'birthday': '1900-01-05T01:00:00Z', - 'length':10.0, - 'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'), - 'species':'dangerous', - }, - { - 'fishtype': 'goblin', - 'age': 1, - 'birthday': '2015-08-08T00:00:00Z', - 'length': 30.0, - 'species': 'scary', - 'jawsize': 5 - } - ] - };. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "fishtype": - - # JSON input template for discriminator value "smart_salmon": - fish = { - "college_degree": "str", # Optional. - "fishtype": "smart_salmon", - "iswild": bool, # Optional. - "length": 0.0, # Required. - "location": "str", # Optional. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template for discriminator value "cookiecuttershark": - fish = { - "age": 0, # Optional. - "birthday": "2020-02-20 00:00:00", # Required. - "fishtype": "cookiecuttershark", - "length": 0.0, # Required. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template for discriminator value "goblin": - fish = { - "age": 0, # Optional. - "birthday": "2020-02-20 00:00:00", # Required. - "color": "gray", # Optional. Default value is "gray". Colors possible. Known - values are: "pink", "gray", "brown", "RED", and "red". - "fishtype": "goblin", - "jawsize": 0, # Optional. - "length": 0.0, # Required. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template for discriminator value "sawshark": - fish = { - "age": 0, # Optional. - "birthday": "2020-02-20 00:00:00", # Required. - "fishtype": "sawshark", - "length": 0.0, # Required. - "picture": bytes("bytes", encoding="utf-8"), # Optional. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template you can fill out and use as your body input. - json = fish - """ - - -@overload -def build_put_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types that are polymorphic. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put a salmon that looks like this: - { - 'fishtype':'Salmon', - 'location':'alaska', - 'iswild':true, - 'species':'king', - 'length':1.0, - 'siblings':[ - { - 'fishtype':'Shark', - 'age':6, - 'birthday': '2012-01-05T01:00:00Z', - 'length':20.0, - 'species':'predator', - }, - { - 'fishtype':'Sawshark', - 'age':105, - 'birthday': '1900-01-05T01:00:00Z', - 'length':10.0, - 'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'), - 'species':'dangerous', - }, - { - 'fishtype': 'goblin', - 'age': 1, - 'birthday': '2015-08-08T00:00:00Z', - 'length': 30.0, - 'species': 'scary', - 'jawsize': 5 - } - ] - };. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_valid_request(**kwargs: Any) -> HttpRequest: - """Put complex types that are polymorphic. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put a salmon that looks like this: - { - 'fishtype':'Salmon', - 'location':'alaska', - 'iswild':true, - 'species':'king', - 'length':1.0, - 'siblings':[ - { - 'fishtype':'Shark', - 'age':6, - 'birthday': '2012-01-05T01:00:00Z', - 'length':20.0, - 'species':'predator', - }, - { - 'fishtype':'Sawshark', - 'age':105, - 'birthday': '1900-01-05T01:00:00Z', - 'length':10.0, - 'picture': new Buffer([255, 255, 255, 255, 254]).toString('base64'), - 'species':'dangerous', - }, - { - 'fishtype': 'goblin', - 'age': 1, - 'birthday': '2015-08-08T00:00:00Z', - 'length': 30.0, - 'species': 'scary', - 'jawsize': 5 - } - ] - };. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/polymorphism/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_dot_syntax_request(**kwargs: Any) -> HttpRequest: - """Get complex types that are polymorphic, JSON key contains a dot. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/polymorphism/dotsyntax" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_composed_with_discriminator_request(**kwargs: Any) -> HttpRequest: - """Get complex object composing a polymorphic scalar property and array property with polymorphic - element type, with discriminator specified. Deserialization must NOT fail and use the - discriminator type specified on the wire. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/polymorphism/composedWithDiscriminator" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_composed_without_discriminator_request(**kwargs: Any) -> HttpRequest: - """Get complex object composing a polymorphic scalar property and array property with polymorphic - element type, without discriminator specified on wire. Deserialization must NOT fail and use - the explicit type of the property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/polymorphism/composedWithoutDiscriminator" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_complicated_request(**kwargs: Any) -> HttpRequest: - """Get complex types that are polymorphic, but not at the root of the hierarchy; also have - additional properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/polymorphism/complicated" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_complicated_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types that are polymorphic, but not at the root of the hierarchy; also have - additional properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "fishtype": - - # JSON input template for discriminator value "smart_salmon": - fish = { - "college_degree": "str", # Optional. - "fishtype": "smart_salmon", - "iswild": bool, # Optional. - "length": 0.0, # Required. - "location": "str", # Optional. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template you can fill out and use as your body input. - json = salmon - """ - - -@overload -def build_put_complicated_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types that are polymorphic, but not at the root of the hierarchy; also have - additional properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_complicated_request(**kwargs: Any) -> HttpRequest: - """Put complex types that are polymorphic, but not at the root of the hierarchy; also have - additional properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/polymorphism/complicated" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_missing_discriminator_request( - *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put complex types that are polymorphic, omitting the discriminator. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "fishtype": - - # JSON input template for discriminator value "smart_salmon": - fish = { - "college_degree": "str", # Optional. - "fishtype": "smart_salmon", - "iswild": bool, # Optional. - "length": 0.0, # Required. - "location": "str", # Optional. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template you can fill out and use as your body input. - json = salmon - """ - - -@overload -def build_put_missing_discriminator_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put complex types that are polymorphic, omitting the discriminator. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_missing_discriminator_request(**kwargs: Any) -> HttpRequest: - """Put complex types that are polymorphic, omitting the discriminator. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/polymorphism/missingdiscriminator" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_valid_missing_required_request( - *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put complex types that are polymorphic, attempting to omit required 'birthday' field - the - request should not be allowed from the client. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please attempt put a sawshark that looks like this, the client should not allow - this data to be sent: - { - "fishtype": "sawshark", - "species": "snaggle toothed", - "length": 18.5, - "age": 2, - "birthday": "2013-06-01T01:00:00Z", - "location": "alaska", - "picture": base64(FF FF FF FF FE), - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "birthday": "2012-01-05T01:00:00Z", - "length": 20, - "age": 6 - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "picture": base64(FF FF FF FF FE), - "length": 10, - "age": 105 - } - ] - }. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # The input is polymorphic. The following are possible polymorphic inputs based off - discriminator "fishtype": - - # JSON input template for discriminator value "smart_salmon": - fish = { - "college_degree": "str", # Optional. - "fishtype": "smart_salmon", - "iswild": bool, # Optional. - "length": 0.0, # Required. - "location": "str", # Optional. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template for discriminator value "cookiecuttershark": - fish = { - "age": 0, # Optional. - "birthday": "2020-02-20 00:00:00", # Required. - "fishtype": "cookiecuttershark", - "length": 0.0, # Required. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template for discriminator value "goblin": - fish = { - "age": 0, # Optional. - "birthday": "2020-02-20 00:00:00", # Required. - "color": "gray", # Optional. Default value is "gray". Colors possible. Known - values are: "pink", "gray", "brown", "RED", and "red". - "fishtype": "goblin", - "jawsize": 0, # Optional. - "length": 0.0, # Required. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template for discriminator value "sawshark": - fish = { - "age": 0, # Optional. - "birthday": "2020-02-20 00:00:00", # Required. - "fishtype": "sawshark", - "length": 0.0, # Required. - "picture": bytes("bytes", encoding="utf-8"), # Optional. - "siblings": [ - fish - ], - "species": "str" # Optional. - } - - # JSON input template you can fill out and use as your body input. - json = fish - """ - - -@overload -def build_put_valid_missing_required_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put complex types that are polymorphic, attempting to omit required 'birthday' field - the - request should not be allowed from the client. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please attempt put a sawshark that looks like this, the client should not - allow this data to be sent: - { - "fishtype": "sawshark", - "species": "snaggle toothed", - "length": 18.5, - "age": 2, - "birthday": "2013-06-01T01:00:00Z", - "location": "alaska", - "picture": base64(FF FF FF FF FE), - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "birthday": "2012-01-05T01:00:00Z", - "length": 20, - "age": 6 - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "picture": base64(FF FF FF FF FE), - "length": 10, - "age": 105 - } - ] - }. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_valid_missing_required_request(**kwargs: Any) -> HttpRequest: - """Put complex types that are polymorphic, attempting to omit required 'birthday' field - the - request should not be allowed from the client. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please attempt put a sawshark that looks like this, the client should not allow - this data to be sent: - { - "fishtype": "sawshark", - "species": "snaggle toothed", - "length": 18.5, - "age": 2, - "birthday": "2013-06-01T01:00:00Z", - "location": "alaska", - "picture": base64(FF FF FF FF FE), - "siblings": [ - { - "fishtype": "shark", - "species": "predator", - "birthday": "2012-01-05T01:00:00Z", - "length": 20, - "age": 6 - }, - { - "fishtype": "sawshark", - "species": "dangerous", - "picture": base64(FF FF FF FF FE), - "length": 10, - "age": 105 - } - ] - }. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/polymorphism/missingrequired/invalid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/primitive/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/primitive/__init__.py deleted file mode 100644 index 67b0cae15c0..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/primitive/__init__.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_int_request -from ._request_builders import build_put_int_request -from ._request_builders import build_get_long_request -from ._request_builders import build_put_long_request -from ._request_builders import build_get_float_request -from ._request_builders import build_put_float_request -from ._request_builders import build_get_double_request -from ._request_builders import build_put_double_request -from ._request_builders import build_get_bool_request -from ._request_builders import build_put_bool_request -from ._request_builders import build_get_string_request -from ._request_builders import build_put_string_request -from ._request_builders import build_get_date_request -from ._request_builders import build_put_date_request -from ._request_builders import build_get_date_time_request -from ._request_builders import build_put_date_time_request -from ._request_builders import build_get_date_time_rfc1123_request -from ._request_builders import build_put_date_time_rfc1123_request -from ._request_builders import build_get_duration_request -from ._request_builders import build_put_duration_request -from ._request_builders import build_get_byte_request -from ._request_builders import build_put_byte_request - -__all__ = [ - "build_get_int_request", - "build_put_int_request", - "build_get_long_request", - "build_put_long_request", - "build_get_float_request", - "build_put_float_request", - "build_get_double_request", - "build_put_double_request", - "build_get_bool_request", - "build_put_bool_request", - "build_get_string_request", - "build_put_string_request", - "build_get_date_request", - "build_put_date_request", - "build_get_date_time_request", - "build_put_date_time_request", - "build_get_date_time_rfc1123_request", - "build_put_date_time_rfc1123_request", - "build_get_duration_request", - "build_put_duration_request", - "build_get_byte_request", - "build_put_byte_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/primitive/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/primitive/_request_builders.py deleted file mode 100644 index b7b8a858add..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/primitive/_request_builders.py +++ /dev/null @@ -1,1197 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_int_request(**kwargs: Any) -> HttpRequest: - """Get complex types with integer properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/integer" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_int_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with integer properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put -1 and 2. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "field1": 0, # Optional. - "field2": 0 # Optional. - } - """ - - -@overload -def build_put_int_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with integer properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put -1 and 2. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_int_request(**kwargs: Any) -> HttpRequest: - """Put complex types with integer properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put -1 and 2. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/integer" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_long_request(**kwargs: Any) -> HttpRequest: - """Get complex types with long properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/long" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_long_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with long properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 1099511627775 and -999511627788. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "field1": 0, # Optional. - "field2": 0 # Optional. - } - """ - - -@overload -def build_put_long_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with long properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put 1099511627775 and -999511627788. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_long_request(**kwargs: Any) -> HttpRequest: - """Put complex types with long properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 1099511627775 and -999511627788. Is either a model type or a IO type. - Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/long" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_float_request(**kwargs: Any) -> HttpRequest: - """Get complex types with float properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/float" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_float_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with float properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 1.05 and -0.003. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "field1": 0.0, # Optional. - "field2": 0.0 # Optional. - } - """ - - -@overload -def build_put_float_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with float properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put 1.05 and -0.003. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_float_request(**kwargs: Any) -> HttpRequest: - """Put complex types with float properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 1.05 and -0.003. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/float" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_double_request(**kwargs: Any) -> HttpRequest: - """Get complex types with double properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/double" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_double_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with double properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 3e-100 and - -0.000000000000000000000000000000000000000000000000000000005. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "field1": 0.0, # Optional. - "field_56_zeros_after_the_dot_and_negative_zero_before_dot_and_this_is_a_long_field_name_on_purpose": - 0.0 # Optional. - } - """ - - -@overload -def build_put_double_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with double properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put 3e-100 and - -0.000000000000000000000000000000000000000000000000000000005. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_double_request(**kwargs: Any) -> HttpRequest: - """Put complex types with double properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 3e-100 and - -0.000000000000000000000000000000000000000000000000000000005. Is either a model type or a IO - type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/double" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_bool_request(**kwargs: Any) -> HttpRequest: - """Get complex types with bool properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/bool" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_bool_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with bool properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put true and false. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "field_false": bool, # Optional. - "field_true": bool # Optional. - } - """ - - -@overload -def build_put_bool_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with bool properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put true and false. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_bool_request(**kwargs: Any) -> HttpRequest: - """Put complex types with bool properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put true and false. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/bool" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_string_request(**kwargs: Any) -> HttpRequest: - """Get complex types with string properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/string" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_string_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with string properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 'goodrequest', '', and null. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "empty": "str", # Optional. - "field": "str", # Optional. - "null": "str" # Optional. - } - """ - - -@overload -def build_put_string_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with string properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put 'goodrequest', '', and null. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_string_request(**kwargs: Any) -> HttpRequest: - """Put complex types with string properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 'goodrequest', '', and null. Is either a model type or a IO type. - Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/string" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_date_request(**kwargs: Any) -> HttpRequest: - """Get complex types with date properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/date" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_date_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with date properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put '0001-01-01' and '2016-02-29'. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "field": "2020-02-20", # Optional. - "leap": "2020-02-20" # Optional. - } - """ - - -@overload -def build_put_date_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with date properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put '0001-01-01' and '2016-02-29'. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_date_request(**kwargs: Any) -> HttpRequest: - """Put complex types with date properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put '0001-01-01' and '2016-02-29'. Is either a model type or a IO type. - Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/date" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_date_time_request(**kwargs: Any) -> HttpRequest: - """Get complex types with datetime properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/datetime" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_date_time_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with datetime properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00'. - Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "field": "2020-02-20 00:00:00", # Optional. - "now": "2020-02-20 00:00:00" # Optional. - } - """ - - -@overload -def build_put_date_time_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with datetime properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00'. - Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_date_time_request(**kwargs: Any) -> HttpRequest: - """Put complex types with datetime properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put '0001-01-01T12:00:00-04:00' and '2015-05-18T11:38:00-08:00'. Is - either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/datetime" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_date_time_rfc1123_request(**kwargs: Any) -> HttpRequest: - """Get complex types with datetimeRfc1123 properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/datetimerfc1123" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_date_time_rfc1123_request( - *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put complex types with datetimeRfc1123 properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00 GMT'. - Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "field": "2020-02-20 00:00:00", # Optional. - "now": "2020-02-20 00:00:00" # Optional. - } - """ - - -@overload -def build_put_date_time_rfc1123_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put complex types with datetimeRfc1123 properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00 - GMT'. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_date_time_rfc1123_request(**kwargs: Any) -> HttpRequest: - """Put complex types with datetimeRfc1123 properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 'Mon, 01 Jan 0001 12:00:00 GMT' and 'Mon, 18 May 2015 11:38:00 GMT'. - Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/datetimerfc1123" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_duration_request(**kwargs: Any) -> HttpRequest: - """Get complex types with duration properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/duration" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_duration_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with duration properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 'P123DT22H14M12.011S'. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "field": "1 day, 0:00:00" # Optional. - } - """ - - -@overload -def build_put_duration_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with duration properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put 'P123DT22H14M12.011S'. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_duration_request(**kwargs: Any) -> HttpRequest: - """Put complex types with duration properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put 'P123DT22H14M12.011S'. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/duration" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_byte_request(**kwargs: Any) -> HttpRequest: - """Get complex types with byte properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/byte" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_byte_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with byte properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6). Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "field": bytes("bytes", encoding="utf-8") # Optional. - } - """ - - -@overload -def build_put_byte_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types with byte properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6). - Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_byte_request(**kwargs: Any) -> HttpRequest: - """Put complex types with byte properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Please put non-ascii byte string hex(FF FE FD FC 00 FA F9 F8 F7 F6). Is either a - model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/primitive/byte" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/readonlyproperty/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/readonlyproperty/__init__.py deleted file mode 100644 index a0483f76f03..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/readonlyproperty/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_valid_request -from ._request_builders import build_put_valid_request - -__all__ = [ - "build_get_valid_request", - "build_put_valid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/readonlyproperty/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/readonlyproperty/_request_builders.py deleted file mode 100644 index 8dda6adf075..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/bodycomplexlowlevel/rest/readonlyproperty/_request_builders.py +++ /dev/null @@ -1,128 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_valid_request(**kwargs: Any) -> HttpRequest: - """Get complex types that have readonly properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/readonlyproperty/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_valid_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types that have readonly properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": "str", # Optional. - "size": 0 # Optional. - } - """ - - -@overload -def build_put_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put complex types that have readonly properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_valid_request(**kwargs: Any) -> HttpRequest: - """Put complex types that have readonly properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/complex/readonlyproperty/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/setup.py deleted file mode 100644 index ff9c21f8754..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyComplexLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestcomplextestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestComplexTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/__init__.py deleted file mode 100644 index b4dcf3b9c78..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestDateTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestDateTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_client.py deleted file mode 100644 index ea89fd1baf7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestDateTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestDateTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestDateTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydatelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydatelowlevel.rest import date - >>> request = date.build_get_null_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestDateTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_configuration.py deleted file mode 100644 index f82c8c7ee22..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestDateTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestDateTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestDateTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestdatetestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/__init__.py deleted file mode 100644 index 60701f7ea51..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestDateTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestDateTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_client.py deleted file mode 100644 index ea685231e97..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestDateTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestDateTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestDateTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydatelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydatelowlevel.rest import date - >>> request = date.build_get_null_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestDateTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_configuration.py deleted file mode 100644 index b6aa3ee8416..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestDateTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestDateTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestDateTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestdatetestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/date/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/date/__init__.py deleted file mode 100644 index 532e86e3778..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/date/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_null_request -from ._request_builders import build_get_invalid_date_request -from ._request_builders import build_get_overflow_date_request -from ._request_builders import build_get_underflow_date_request -from ._request_builders import build_put_max_date_request -from ._request_builders import build_get_max_date_request -from ._request_builders import build_put_min_date_request -from ._request_builders import build_get_min_date_request - -__all__ = [ - "build_get_null_request", - "build_get_invalid_date_request", - "build_get_overflow_date_request", - "build_get_underflow_date_request", - "build_put_max_date_request", - "build_get_max_date_request", - "build_put_min_date_request", - "build_get_min_date_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/date/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/date/_request_builders.py deleted file mode 100644 index fb0154b245c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/bodydatelowlevel/rest/date/_request_builders.py +++ /dev/null @@ -1,227 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null date value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/date/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_date_request(**kwargs: Any) -> HttpRequest: - """Get invalid date value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/date/invaliddate" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_overflow_date_request(**kwargs: Any) -> HttpRequest: - """Get overflow date value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/date/overflowdate" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_underflow_date_request(**kwargs: Any) -> HttpRequest: - """Get underflow date value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/date/underflowdate" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_max_date_request(*, json: datetime.date, **kwargs: Any) -> HttpRequest: - """Put max date value 9999-12-31. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: date body. Required. - :paramtype json: ~datetime.date - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/date/max" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_max_date_request(**kwargs: Any) -> HttpRequest: - """Get max date value 9999-12-31. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/date/max" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_min_date_request(*, json: datetime.date, **kwargs: Any) -> HttpRequest: - """Put min date value 0000-01-01. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: date body. Required. - :paramtype json: ~datetime.date - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/date/min" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_min_date_request(**kwargs: Any) -> HttpRequest: - """Get min date value 0000-01-01. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/date/min" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/setup.py deleted file mode 100644 index e24423edc7c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestdatetestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestDateTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/__init__.py deleted file mode 100644 index b39b8e8fb79..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestDateTimeTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestDateTimeTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_client.py deleted file mode 100644 index 723d904695c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestDateTimeTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestDateTimeTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestDateTimeTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydatetimelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydatetimelowlevel.rest import datetime - >>> request = datetime.build_get_null_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestDateTimeTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_configuration.py deleted file mode 100644 index 6eececda5b9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestDateTimeTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestDateTimeTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestDateTimeTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestdatetimetestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/__init__.py deleted file mode 100644 index ce6abd839ba..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestDateTimeTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestDateTimeTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_client.py deleted file mode 100644 index 1680b7e784f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestDateTimeTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestDateTimeTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestDateTimeTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydatetimelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydatetimelowlevel.rest import datetime - >>> request = datetime.build_get_null_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestDateTimeTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_configuration.py deleted file mode 100644 index 6d637375ab1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestDateTimeTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestDateTimeTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestDateTimeTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestdatetimetestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/datetime/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/datetime/__init__.py deleted file mode 100644 index 801406bf87f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/datetime/__init__.py +++ /dev/null @@ -1,55 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_null_request -from ._request_builders import build_get_invalid_request -from ._request_builders import build_get_overflow_request -from ._request_builders import build_get_underflow_request -from ._request_builders import build_put_utc_max_date_time_request -from ._request_builders import build_put_utc_max_date_time7_digits_request -from ._request_builders import build_get_utc_lowercase_max_date_time_request -from ._request_builders import build_get_utc_uppercase_max_date_time_request -from ._request_builders import build_get_utc_uppercase_max_date_time7_digits_request -from ._request_builders import build_put_local_positive_offset_max_date_time_request -from ._request_builders import build_get_local_positive_offset_lowercase_max_date_time_request -from ._request_builders import build_get_local_positive_offset_uppercase_max_date_time_request -from ._request_builders import build_put_local_negative_offset_max_date_time_request -from ._request_builders import build_get_local_negative_offset_uppercase_max_date_time_request -from ._request_builders import build_get_local_negative_offset_lowercase_max_date_time_request -from ._request_builders import build_put_utc_min_date_time_request -from ._request_builders import build_get_utc_min_date_time_request -from ._request_builders import build_put_local_positive_offset_min_date_time_request -from ._request_builders import build_get_local_positive_offset_min_date_time_request -from ._request_builders import build_put_local_negative_offset_min_date_time_request -from ._request_builders import build_get_local_negative_offset_min_date_time_request -from ._request_builders import build_get_local_no_offset_min_date_time_request - -__all__ = [ - "build_get_null_request", - "build_get_invalid_request", - "build_get_overflow_request", - "build_get_underflow_request", - "build_put_utc_max_date_time_request", - "build_put_utc_max_date_time7_digits_request", - "build_get_utc_lowercase_max_date_time_request", - "build_get_utc_uppercase_max_date_time_request", - "build_get_utc_uppercase_max_date_time7_digits_request", - "build_put_local_positive_offset_max_date_time_request", - "build_get_local_positive_offset_lowercase_max_date_time_request", - "build_get_local_positive_offset_uppercase_max_date_time_request", - "build_put_local_negative_offset_max_date_time_request", - "build_get_local_negative_offset_uppercase_max_date_time_request", - "build_get_local_negative_offset_lowercase_max_date_time_request", - "build_put_utc_min_date_time_request", - "build_get_utc_min_date_time_request", - "build_put_local_positive_offset_min_date_time_request", - "build_get_local_positive_offset_min_date_time_request", - "build_put_local_negative_offset_min_date_time_request", - "build_get_local_negative_offset_min_date_time_request", - "build_get_local_no_offset_min_date_time_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/datetime/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/datetime/_request_builders.py deleted file mode 100644 index 8dbac747c51..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/bodydatetimelowlevel/rest/datetime/_request_builders.py +++ /dev/null @@ -1,608 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null datetime value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_request(**kwargs: Any) -> HttpRequest: - """Get invalid datetime value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_overflow_request(**kwargs: Any) -> HttpRequest: - """Get overflow datetime value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/overflow" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_underflow_request(**kwargs: Any) -> HttpRequest: - """Get underflow datetime value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/underflow" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_utc_max_date_time_request(*, json: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Put max datetime value 9999-12-31T23:59:59.999Z. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: datetime body. Required. - :paramtype json: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/max/utc" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_put_utc_max_date_time7_digits_request(*, json: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Put max datetime value 9999-12-31T23:59:59.9999999Z. - - This is against the recommendation that asks for 3 digits, but allow to test what happens in - that scenario. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: datetime body. Required. - :paramtype json: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/max/utc7ms" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_utc_lowercase_max_date_time_request(**kwargs: Any) -> HttpRequest: - """Get max datetime value 9999-12-31t23:59:59.999z. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/max/utc/lowercase" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_utc_uppercase_max_date_time_request(**kwargs: Any) -> HttpRequest: - """Get max datetime value 9999-12-31T23:59:59.999Z. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/max/utc/uppercase" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_utc_uppercase_max_date_time7_digits_request(**kwargs: Any) -> HttpRequest: - """Get max datetime value 9999-12-31T23:59:59.9999999Z. - - This is against the recommendation that asks for 3 digits, but allow to test what happens in - that scenario. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/max/utc7ms/uppercase" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_local_positive_offset_max_date_time_request(*, json: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Put max datetime value with positive numoffset 9999-12-31t23:59:59.999+14:00. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: datetime body. Required. - :paramtype json: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/max/localpositiveoffset" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_local_positive_offset_lowercase_max_date_time_request(**kwargs: Any) -> HttpRequest: - """Get max datetime value with positive num offset 9999-12-31t23:59:59.999+14:00. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/max/localpositiveoffset/lowercase" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_local_positive_offset_uppercase_max_date_time_request(**kwargs: Any) -> HttpRequest: - """Get max datetime value with positive num offset 9999-12-31T23:59:59.999+14:00. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/max/localpositiveoffset/uppercase" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_local_negative_offset_max_date_time_request(*, json: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Put max datetime value with positive numoffset 9999-12-31t23:59:59.999-14:00. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: datetime body. Required. - :paramtype json: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/max/localnegativeoffset" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_local_negative_offset_uppercase_max_date_time_request(**kwargs: Any) -> HttpRequest: - """Get max datetime value with positive num offset 9999-12-31T23:59:59.999-14:00. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/max/localnegativeoffset/uppercase" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_local_negative_offset_lowercase_max_date_time_request(**kwargs: Any) -> HttpRequest: - """Get max datetime value with positive num offset 9999-12-31t23:59:59.999-14:00. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/max/localnegativeoffset/lowercase" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_utc_min_date_time_request(*, json: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Put min datetime value 0001-01-01T00:00:00Z. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: datetime body. Required. - :paramtype json: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/min/utc" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_utc_min_date_time_request(**kwargs: Any) -> HttpRequest: - """Get min datetime value 0001-01-01T00:00:00Z. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/min/utc" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_local_positive_offset_min_date_time_request(*, json: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Put min datetime value 0001-01-01T00:00:00+14:00. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: datetime body. Required. - :paramtype json: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/min/localpositiveoffset" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_local_positive_offset_min_date_time_request(**kwargs: Any) -> HttpRequest: - """Get min datetime value 0001-01-01T00:00:00+14:00. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/min/localpositiveoffset" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_local_negative_offset_min_date_time_request(*, json: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Put min datetime value 0001-01-01T00:00:00-14:00. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: datetime body. Required. - :paramtype json: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/min/localnegativeoffset" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_local_negative_offset_min_date_time_request(**kwargs: Any) -> HttpRequest: - """Get min datetime value 0001-01-01T00:00:00-14:00. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/min/localnegativeoffset" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_local_no_offset_min_date_time_request(**kwargs: Any) -> HttpRequest: - """Get min datetime value 0001-01-01T00:00:00. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetime/min/localnooffset" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/setup.py deleted file mode 100644 index 878f4dbad19..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestdatetimetestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestDateTimeTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/__init__.py deleted file mode 100644 index 22443b8eb94..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestRFC1123DateTimeTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestRFC1123DateTimeTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_client.py deleted file mode 100644 index 8f4e1083fa7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestRFC1123DateTimeTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestRFC1123DateTimeTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestRFC1123DateTimeTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydatetimerfc1123lowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydatetimerfc1123lowlevel.rest import datetimerfc1123 - >>> request = datetimerfc1123.build_get_null_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestRFC1123DateTimeTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_configuration.py deleted file mode 100644 index 8987dad58ea..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestRFC1123DateTimeTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestRFC1123DateTimeTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestRFC1123DateTimeTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestrfc1123datetimetestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/__init__.py deleted file mode 100644 index f877061a69d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestRFC1123DateTimeTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestRFC1123DateTimeTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_client.py deleted file mode 100644 index 280d7882754..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestRFC1123DateTimeTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestRFC1123DateTimeTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestRFC1123DateTimeTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydatetimerfc1123lowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydatetimerfc1123lowlevel.rest import datetimerfc1123 - >>> request = datetimerfc1123.build_get_null_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestRFC1123DateTimeTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_configuration.py deleted file mode 100644 index 0ab8b3ec958..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestRFC1123DateTimeTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestRFC1123DateTimeTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestRFC1123DateTimeTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestrfc1123datetimetestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/datetimerfc1123/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/datetimerfc1123/__init__.py deleted file mode 100644 index 81753c44f04..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/datetimerfc1123/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_null_request -from ._request_builders import build_get_invalid_request -from ._request_builders import build_get_overflow_request -from ._request_builders import build_get_underflow_request -from ._request_builders import build_put_utc_max_date_time_request -from ._request_builders import build_get_utc_lowercase_max_date_time_request -from ._request_builders import build_get_utc_uppercase_max_date_time_request -from ._request_builders import build_put_utc_min_date_time_request -from ._request_builders import build_get_utc_min_date_time_request - -__all__ = [ - "build_get_null_request", - "build_get_invalid_request", - "build_get_overflow_request", - "build_get_underflow_request", - "build_put_utc_max_date_time_request", - "build_get_utc_lowercase_max_date_time_request", - "build_get_utc_uppercase_max_date_time_request", - "build_put_utc_min_date_time_request", - "build_get_utc_min_date_time_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/datetimerfc1123/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/datetimerfc1123/_request_builders.py deleted file mode 100644 index a19fe59b477..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/bodydatetimerfc1123lowlevel/rest/datetimerfc1123/_request_builders.py +++ /dev/null @@ -1,252 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null datetime value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetimerfc1123/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_request(**kwargs: Any) -> HttpRequest: - """Get invalid datetime value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetimerfc1123/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_overflow_request(**kwargs: Any) -> HttpRequest: - """Get overflow datetime value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetimerfc1123/overflow" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_underflow_request(**kwargs: Any) -> HttpRequest: - """Get underflow datetime value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetimerfc1123/underflow" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_utc_max_date_time_request(*, json: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Put max datetime value Fri, 31 Dec 9999 23:59:59 GMT. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: datetime body. Required. - :paramtype json: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetimerfc1123/max" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_utc_lowercase_max_date_time_request(**kwargs: Any) -> HttpRequest: - """Get max datetime value fri, 31 dec 9999 23:59:59 gmt. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetimerfc1123/max/lowercase" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_utc_uppercase_max_date_time_request(**kwargs: Any) -> HttpRequest: - """Get max datetime value FRI, 31 DEC 9999 23:59:59 GMT. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetimerfc1123/max/uppercase" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_utc_min_date_time_request(*, json: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Put min datetime value Mon, 1 Jan 0001 00:00:00 GMT. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: datetime body. Required. - :paramtype json: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetimerfc1123/min" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_utc_min_date_time_request(**kwargs: Any) -> HttpRequest: - """Get min datetime value Mon, 1 Jan 0001 00:00:00 GMT. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/datetimerfc1123/min" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/setup.py deleted file mode 100644 index 750f1a87db1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestrfc1123datetimetestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestRFC1123DateTimeTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/__init__.py deleted file mode 100644 index ca4851095bd..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATDictionaryService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATDictionaryService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_client.py deleted file mode 100644 index dae4ed498f0..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestSwaggerBATDictionaryServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATDictionaryService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATDictionaryServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydictionarylowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydictionarylowlevel.rest import dictionary - >>> request = dictionary.build_get_null_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestSwaggerBATDictionaryService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_configuration.py deleted file mode 100644 index cff1e0e3d53..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestSwaggerBATDictionaryServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATDictionaryService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATDictionaryServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatdictionaryservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/__init__.py deleted file mode 100644 index 1ef816b44e5..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATDictionaryService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATDictionaryService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_client.py deleted file mode 100644 index 46af3aa027a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestSwaggerBATDictionaryServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATDictionaryService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATDictionaryServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydictionarylowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydictionarylowlevel.rest import dictionary - >>> request = dictionary.build_get_null_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestSwaggerBATDictionaryService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_configuration.py deleted file mode 100644 index 7efa1013d5e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestSwaggerBATDictionaryServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATDictionaryService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATDictionaryServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatdictionaryservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/dictionary/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/dictionary/__init__.py deleted file mode 100644 index 02fe0307deb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/dictionary/__init__.py +++ /dev/null @@ -1,141 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_null_request -from ._request_builders import build_get_empty_request -from ._request_builders import build_put_empty_request -from ._request_builders import build_get_null_value_request -from ._request_builders import build_get_null_key_request -from ._request_builders import build_get_empty_string_key_request -from ._request_builders import build_get_invalid_request -from ._request_builders import build_get_boolean_tfft_request -from ._request_builders import build_put_boolean_tfft_request -from ._request_builders import build_get_boolean_invalid_null_request -from ._request_builders import build_get_boolean_invalid_string_request -from ._request_builders import build_get_integer_valid_request -from ._request_builders import build_put_integer_valid_request -from ._request_builders import build_get_int_invalid_null_request -from ._request_builders import build_get_int_invalid_string_request -from ._request_builders import build_get_long_valid_request -from ._request_builders import build_put_long_valid_request -from ._request_builders import build_get_long_invalid_null_request -from ._request_builders import build_get_long_invalid_string_request -from ._request_builders import build_get_float_valid_request -from ._request_builders import build_put_float_valid_request -from ._request_builders import build_get_float_invalid_null_request -from ._request_builders import build_get_float_invalid_string_request -from ._request_builders import build_get_double_valid_request -from ._request_builders import build_put_double_valid_request -from ._request_builders import build_get_double_invalid_null_request -from ._request_builders import build_get_double_invalid_string_request -from ._request_builders import build_get_string_valid_request -from ._request_builders import build_put_string_valid_request -from ._request_builders import build_get_string_with_null_request -from ._request_builders import build_get_string_with_invalid_request -from ._request_builders import build_get_date_valid_request -from ._request_builders import build_put_date_valid_request -from ._request_builders import build_get_date_invalid_null_request -from ._request_builders import build_get_date_invalid_chars_request -from ._request_builders import build_get_date_time_valid_request -from ._request_builders import build_put_date_time_valid_request -from ._request_builders import build_get_date_time_invalid_null_request -from ._request_builders import build_get_date_time_invalid_chars_request -from ._request_builders import build_get_date_time_rfc1123_valid_request -from ._request_builders import build_put_date_time_rfc1123_valid_request -from ._request_builders import build_get_duration_valid_request -from ._request_builders import build_put_duration_valid_request -from ._request_builders import build_get_byte_valid_request -from ._request_builders import build_put_byte_valid_request -from ._request_builders import build_get_byte_invalid_null_request -from ._request_builders import build_get_base64_url_request -from ._request_builders import build_get_complex_null_request -from ._request_builders import build_get_complex_empty_request -from ._request_builders import build_get_complex_item_null_request -from ._request_builders import build_get_complex_item_empty_request -from ._request_builders import build_get_complex_valid_request -from ._request_builders import build_put_complex_valid_request -from ._request_builders import build_get_array_null_request -from ._request_builders import build_get_array_empty_request -from ._request_builders import build_get_array_item_null_request -from ._request_builders import build_get_array_item_empty_request -from ._request_builders import build_get_array_valid_request -from ._request_builders import build_put_array_valid_request -from ._request_builders import build_get_dictionary_null_request -from ._request_builders import build_get_dictionary_empty_request -from ._request_builders import build_get_dictionary_item_null_request -from ._request_builders import build_get_dictionary_item_empty_request -from ._request_builders import build_get_dictionary_valid_request -from ._request_builders import build_put_dictionary_valid_request - -__all__ = [ - "build_get_null_request", - "build_get_empty_request", - "build_put_empty_request", - "build_get_null_value_request", - "build_get_null_key_request", - "build_get_empty_string_key_request", - "build_get_invalid_request", - "build_get_boolean_tfft_request", - "build_put_boolean_tfft_request", - "build_get_boolean_invalid_null_request", - "build_get_boolean_invalid_string_request", - "build_get_integer_valid_request", - "build_put_integer_valid_request", - "build_get_int_invalid_null_request", - "build_get_int_invalid_string_request", - "build_get_long_valid_request", - "build_put_long_valid_request", - "build_get_long_invalid_null_request", - "build_get_long_invalid_string_request", - "build_get_float_valid_request", - "build_put_float_valid_request", - "build_get_float_invalid_null_request", - "build_get_float_invalid_string_request", - "build_get_double_valid_request", - "build_put_double_valid_request", - "build_get_double_invalid_null_request", - "build_get_double_invalid_string_request", - "build_get_string_valid_request", - "build_put_string_valid_request", - "build_get_string_with_null_request", - "build_get_string_with_invalid_request", - "build_get_date_valid_request", - "build_put_date_valid_request", - "build_get_date_invalid_null_request", - "build_get_date_invalid_chars_request", - "build_get_date_time_valid_request", - "build_put_date_time_valid_request", - "build_get_date_time_invalid_null_request", - "build_get_date_time_invalid_chars_request", - "build_get_date_time_rfc1123_valid_request", - "build_put_date_time_rfc1123_valid_request", - "build_get_duration_valid_request", - "build_put_duration_valid_request", - "build_get_byte_valid_request", - "build_put_byte_valid_request", - "build_get_byte_invalid_null_request", - "build_get_base64_url_request", - "build_get_complex_null_request", - "build_get_complex_empty_request", - "build_get_complex_item_null_request", - "build_get_complex_item_empty_request", - "build_get_complex_valid_request", - "build_put_complex_valid_request", - "build_get_array_null_request", - "build_get_array_empty_request", - "build_get_array_item_null_request", - "build_get_array_item_empty_request", - "build_get_array_valid_request", - "build_put_array_valid_request", - "build_get_dictionary_null_request", - "build_get_dictionary_empty_request", - "build_get_dictionary_item_null_request", - "build_get_dictionary_item_empty_request", - "build_get_dictionary_valid_request", - "build_put_dictionary_valid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/dictionary/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/dictionary/_request_builders.py deleted file mode 100644 index cc339f92eb9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/bodydictionarylowlevel/rest/dictionary/_request_builders.py +++ /dev/null @@ -1,2532 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -import sys -from typing import Any, Dict, IO, List, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null dictionary value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_empty_request(**kwargs: Any) -> HttpRequest: - """Get empty dictionary value {}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_empty_request(*, json: Dict[str, str], content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set dictionary value empty {}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, str] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": "str" # Optional. - } - """ - - -@overload -def build_put_empty_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set dictionary value empty {}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_empty_request(**kwargs: Any) -> HttpRequest: - """Set dictionary value empty {}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, str] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/empty" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_null_value_request(**kwargs: Any) -> HttpRequest: - """Get Dictionary with null value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/nullvalue" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_null_key_request(**kwargs: Any) -> HttpRequest: - """Get Dictionary with null key. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/nullkey" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_empty_string_key_request(**kwargs: Any) -> HttpRequest: - """Get Dictionary with key as empty string. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/keyemptystring" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_request(**kwargs: Any) -> HttpRequest: - """Get invalid Dictionary value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_boolean_tfft_request(**kwargs: Any) -> HttpRequest: - """Get boolean dictionary value {"0": true, "1": false, "2": false, "3": true }. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/boolean/tfft" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_boolean_tfft_request( - *, json: Dict[str, bool], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set dictionary value empty {"0": true, "1": false, "2": false, "3": true }. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, bool] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": bool # Optional. - } - """ - - -@overload -def build_put_boolean_tfft_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set dictionary value empty {"0": true, "1": false, "2": false, "3": true }. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_boolean_tfft_request(**kwargs: Any) -> HttpRequest: - """Set dictionary value empty {"0": true, "1": false, "2": false, "3": true }. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, bool] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/boolean/tfft" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_boolean_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get boolean dictionary value {"0": true, "1": null, "2": false }. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/boolean/true.null.false" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_boolean_invalid_string_request(**kwargs: Any) -> HttpRequest: - """Get boolean dictionary value '{"0": true, "1": "boolean", "2": false}'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/boolean/true.boolean.false" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_integer_valid_request(**kwargs: Any) -> HttpRequest: - """Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/integer/1.-1.3.300" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_integer_valid_request( - *, json: Dict[str, int], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, int] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": 0 # Optional. - } - """ - - -@overload -def build_put_integer_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_integer_valid_request(**kwargs: Any) -> HttpRequest: - """Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, int] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/integer/1.-1.3.300" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_int_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get integer dictionary value {"0": 1, "1": null, "2": 0}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/integer/1.null.zero" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_int_invalid_string_request(**kwargs: Any) -> HttpRequest: - """Get integer dictionary value {"0": 1, "1": "integer", "2": 0}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/integer/1.integer.0" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_long_valid_request(**kwargs: Any) -> HttpRequest: - """Get integer dictionary value {"0": 1, "1": -1, "2": 3, "3": 300}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/long/1.-1.3.300" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_long_valid_request( - *, json: Dict[str, int], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, int] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": 0 # Optional. - } - """ - - -@overload -def build_put_long_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_long_valid_request(**kwargs: Any) -> HttpRequest: - """Set dictionary value empty {"0": 1, "1": -1, "2": 3, "3": 300}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, int] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/long/1.-1.3.300" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_long_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get long dictionary value {"0": 1, "1": null, "2": 0}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/long/1.null.zero" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_long_invalid_string_request(**kwargs: Any) -> HttpRequest: - """Get long dictionary value {"0": 1, "1": "integer", "2": 0}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/long/1.integer.0" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_float_valid_request(**kwargs: Any) -> HttpRequest: - """Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/float/0--0.01-1.2e20" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_float_valid_request( - *, json: Dict[str, float], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, float] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": 0.0 # Optional. - } - """ - - -@overload -def build_put_float_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_float_valid_request(**kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, float] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/float/0--0.01-1.2e20" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_float_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/float/0.0-null-1.2e20" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_float_invalid_string_request(**kwargs: Any) -> HttpRequest: - """Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/float/1.number.0" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_double_valid_request(**kwargs: Any) -> HttpRequest: - """Get float dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/double/0--0.01-1.2e20" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_double_valid_request( - *, json: Dict[str, float], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, float] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": 0.0 # Optional. - } - """ - - -@overload -def build_put_double_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_double_valid_request(**kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": 0, "1": -0.01, "2": 1.2e20}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, float] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/double/0--0.01-1.2e20" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_double_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get float dictionary value {"0": 0.0, "1": null, "2": 1.2e20}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/double/0.0-null-1.2e20" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_double_invalid_string_request(**kwargs: Any) -> HttpRequest: - """Get boolean dictionary value {"0": 1.0, "1": "number", "2": 0.0}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/double/1.number.0" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_string_valid_request(**kwargs: Any) -> HttpRequest: - """Get string dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/string/foo1.foo2.foo3" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_string_valid_request( - *, json: Dict[str, str], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, str] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": "str" # Optional. - } - """ - - -@overload -def build_put_string_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_string_valid_request(**kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": "foo1", "1": "foo2", "2": "foo3"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, str] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/string/foo1.foo2.foo3" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_string_with_null_request(**kwargs: Any) -> HttpRequest: - """Get string dictionary value {"0": "foo", "1": null, "2": "foo2"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/string/foo.null.foo2" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_string_with_invalid_request(**kwargs: Any) -> HttpRequest: - """Get string dictionary value {"0": "foo", "1": 123, "2": "foo2"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/string/foo.123.foo2" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_date_valid_request(**kwargs: Any) -> HttpRequest: - """Get integer dictionary value {"0": "2000-12-01", "1": "1980-01-02", "2": "1492-10-12"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/date/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_date_valid_request( - *, json: Dict[str, datetime.date], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set dictionary value {"0": "2000-12-01", "1": "1980-01-02", "2": "1492-10-12"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, ~datetime.date] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": "2020-02-20" # Optional. - } - """ - - -@overload -def build_put_date_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": "2000-12-01", "1": "1980-01-02", "2": "1492-10-12"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_date_valid_request(**kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": "2000-12-01", "1": "1980-01-02", "2": "1492-10-12"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, ~datetime.date] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/date/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_date_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get date dictionary value {"0": "2012-01-01", "1": null, "2": "1776-07-04"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/date/invalidnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_date_invalid_chars_request(**kwargs: Any) -> HttpRequest: - """Get date dictionary value {"0": "2011-03-22", "1": "date"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/date/invalidchars" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_date_time_valid_request(**kwargs: Any) -> HttpRequest: - """Get date-time dictionary value {"0": "2000-12-01t00:00:01z", "1": "1980-01-02T00:11:35+01:00", - "2": "1492-10-12T10:15:01-08:00"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/date-time/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_date_time_valid_request( - *, json: Dict[str, datetime.datetime], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set dictionary value {"0": "2000-12-01t00:00:01z", "1": "1980-01-02T00:11:35+01:00", "2": - "1492-10-12T10:15:01-08:00"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, ~datetime.datetime] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": "2020-02-20 00:00:00" # Optional. - } - """ - - -@overload -def build_put_date_time_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": "2000-12-01t00:00:01z", "1": "1980-01-02T00:11:35+01:00", "2": - "1492-10-12T10:15:01-08:00"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_date_time_valid_request(**kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": "2000-12-01t00:00:01z", "1": "1980-01-02T00:11:35+01:00", "2": - "1492-10-12T10:15:01-08:00"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, ~datetime.datetime] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/date-time/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_date_time_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": null}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/date-time/invalidnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_date_time_invalid_chars_request(**kwargs: Any) -> HttpRequest: - """Get date dictionary value {"0": "2000-12-01t00:00:01z", "1": "date-time"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/date-time/invalidchars" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_date_time_rfc1123_valid_request(**kwargs: Any) -> HttpRequest: - """Get date-time-rfc1123 dictionary value {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan - 1980 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/date-time-rfc1123/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_date_time_rfc1123_valid_request( - *, json: Dict[str, datetime.datetime], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set dictionary value empty {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980 - 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, ~datetime.datetime] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": "2020-02-20 00:00:00" # Optional. - } - """ - - -@overload -def build_put_date_time_rfc1123_valid_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set dictionary value empty {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980 - 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_date_time_rfc1123_valid_request(**kwargs: Any) -> HttpRequest: - """Set dictionary value empty {"0": "Fri, 01 Dec 2000 00:00:01 GMT", "1": "Wed, 02 Jan 1980 - 00:11:35 GMT", "2": "Wed, 12 Oct 1492 10:15:01 GMT"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, ~datetime.datetime] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/date-time-rfc1123/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_duration_valid_request(**kwargs: Any) -> HttpRequest: - """Get duration dictionary value {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/duration/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_duration_valid_request( - *, json: Dict[str, datetime.timedelta], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Set dictionary value {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, ~datetime.timedelta] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": "1 day, 0:00:00" # Optional. - } - """ - - -@overload -def build_put_duration_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_duration_valid_request(**kwargs: Any) -> HttpRequest: - """Set dictionary value {"0": "P123DT22H14M12.011S", "1": "P5DT1H0M0S"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, ~datetime.timedelta] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/duration/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_byte_valid_request(**kwargs: Any) -> HttpRequest: - """Get byte dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 03), "2": hex (25, 29, 43)} - with each item encoded in base64. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/byte/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_byte_valid_request( - *, json: Dict[str, bytes], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put the dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 03), "2": hex (25, 29, 43)} - with each elementencoded in base 64. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, bytes] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": bytes("bytes", encoding="utf-8") # Optional. - } - """ - - -@overload -def build_put_byte_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put the dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 03), "2": hex (25, 29, 43)} - with each elementencoded in base 64. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_byte_valid_request(**kwargs: Any) -> HttpRequest: - """Put the dictionary value {"0": hex(FF FF FF FA), "1": hex(01 02 03), "2": hex (25, 29, 43)} - with each elementencoded in base 64. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, bytes] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/byte/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_byte_invalid_null_request(**kwargs: Any) -> HttpRequest: - """Get byte dictionary value {"0": hex(FF FF FF FA), "1": null} with the first item base64 - encoded. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/byte/invalidnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_base64_url_request(**kwargs: Any) -> HttpRequest: - """Get base64url dictionary value {"0": "a string that gets encoded with base64url", "1": "test - string", "2": "Lorem ipsum"}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/prim/base64url/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_complex_null_request(**kwargs: Any) -> HttpRequest: - """Get dictionary of complex type null value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/complex/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_complex_empty_request(**kwargs: Any) -> HttpRequest: - """Get empty dictionary of complex type {}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/complex/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_complex_item_null_request(**kwargs: Any) -> HttpRequest: - """Get dictionary of complex type with null item {"0": {"integer": 1, "string": "2"}, "1": null, - "2": {"integer": 5, "string": "6"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/complex/itemnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_complex_item_empty_request(**kwargs: Any) -> HttpRequest: - """Get dictionary of complex type with empty item {"0": {"integer": 1, "string": "2"}, "1:" {}, - "2": {"integer": 5, "string": "6"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/complex/itemempty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_complex_valid_request(**kwargs: Any) -> HttpRequest: - """Get dictionary of complex type with {"0": {"integer": 1, "string": "2"}, "1": {"integer": 3, - "string": "4"}, "2": {"integer": 5, "string": "6"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/complex/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_complex_valid_request( - *, json: Dict[str, JSON], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put an dictionary of complex type with values {"0": {"integer": 1, "string": "2"}, "1": - {"integer": 3, "string": "4"}, "2": {"integer": 5, "string": "6"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, JSON] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": { - "integer": 0, # Optional. - "string": "str" # Optional. - } - } - """ - - -@overload -def build_put_complex_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put an dictionary of complex type with values {"0": {"integer": 1, "string": "2"}, "1": - {"integer": 3, "string": "4"}, "2": {"integer": 5, "string": "6"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_complex_valid_request(**kwargs: Any) -> HttpRequest: - """Put an dictionary of complex type with values {"0": {"integer": 1, "string": "2"}, "1": - {"integer": 3, "string": "4"}, "2": {"integer": 5, "string": "6"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, JSON] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/complex/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_array_null_request(**kwargs: Any) -> HttpRequest: - """Get a null array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/array/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_array_empty_request(**kwargs: Any) -> HttpRequest: - """Get an empty dictionary {}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/array/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_array_item_null_request(**kwargs: Any) -> HttpRequest: - """Get an dictionary of array of strings {"0": ["1", "2", "3"], "1": null, "2": ["7", "8", "9"]}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/array/itemnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_array_item_empty_request(**kwargs: Any) -> HttpRequest: - """Get an array of array of strings [{"0": ["1", "2", "3"], "1": [], "2": ["7", "8", "9"]}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/array/itemempty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_array_valid_request(**kwargs: Any) -> HttpRequest: - """Get an array of array of strings {"0": ["1", "2", "3"], "1": ["4", "5", "6"], "2": ["7", "8", - "9"]}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/array/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_array_valid_request( - *, json: Dict[str, List[str]], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Put An array of array of strings {"0": ["1", "2", "3"], "1": ["4", "5", "6"], "2": ["7", "8", - "9"]}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, list[str]] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": [ - "str" # Optional. - ] - } - """ - - -@overload -def build_put_array_valid_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put An array of array of strings {"0": ["1", "2", "3"], "1": ["4", "5", "6"], "2": ["7", "8", - "9"]}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_array_valid_request(**kwargs: Any) -> HttpRequest: - """Put An array of array of strings {"0": ["1", "2", "3"], "1": ["4", "5", "6"], "2": ["7", "8", - "9"]}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, list[str]] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/array/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_dictionary_null_request(**kwargs: Any) -> HttpRequest: - """Get an dictionaries of dictionaries with value null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/dictionary/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_dictionary_empty_request(**kwargs: Any) -> HttpRequest: - """Get an dictionaries of dictionaries of type with value {}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/dictionary/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_dictionary_item_null_request(**kwargs: Any) -> HttpRequest: - """Get an dictionaries of dictionaries of type with value {"0": {"1": "one", "2": - "two", "3": "three"}, "1": null, "2": {"7": "seven", "8": "eight", "9": "nine"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/dictionary/itemnull" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_dictionary_item_empty_request(**kwargs: Any) -> HttpRequest: - """Get an dictionaries of dictionaries of type with value {"0": {"1": "one", "2": - "two", "3": "three"}, "1": {}, "2": {"7": "seven", "8": "eight", "9": "nine"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/dictionary/itemempty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_dictionary_valid_request(**kwargs: Any) -> HttpRequest: - """Get an dictionaries of dictionaries of type with value {"0": {"1": "one", "2": - "two", "3": "three"}, "1": {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": - "eight", "9": "nine"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/dictionary/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_dictionary_valid_request( - *, json: Dict[str, Dict[str, str]], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Get an dictionaries of dictionaries of type with value {"0": {"1": "one", "2": - "two", "3": "three"}, "1": {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": - "eight", "9": "nine"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: dict[str, dict[str, str]] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": { - "str": "str" # Optional. - } - } - """ - - -@overload -def build_put_dictionary_valid_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Get an dictionaries of dictionaries of type with value {"0": {"1": "one", "2": - "two", "3": "three"}, "1": {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": - "eight", "9": "nine"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_dictionary_valid_request(**kwargs: Any) -> HttpRequest: - """Get an dictionaries of dictionaries of type with value {"0": {"1": "one", "2": - "two", "3": "three"}, "1": {"4": "four", "5": "five", "6": "six"}, "2": {"7": "seven", "8": - "eight", "9": "nine"}}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a dict type or a IO type. Required. - :paramtype json: dict[str, dict[str, str]] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/dictionary/dictionary/valid" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/setup.py deleted file mode 100644 index 23047eeacd7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDictionaryLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestswaggerbatdictionaryservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestSwaggerBATDictionaryService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest Swagger BAT. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/__init__.py deleted file mode 100644 index 44c09782afe..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestDurationTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestDurationTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_client.py deleted file mode 100644 index cf207cd4ee4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestDurationTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestDurationTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestDurationTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydurationlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydurationlowlevel.rest import duration - >>> request = duration.build_get_null_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestDurationTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_configuration.py deleted file mode 100644 index d3e575e957c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestDurationTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestDurationTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestDurationTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestdurationtestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/__init__.py deleted file mode 100644 index a58fa28f613..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestDurationTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestDurationTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_client.py deleted file mode 100644 index 0570d4fbe93..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestDurationTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestDurationTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestDurationTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodydurationlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodydurationlowlevel.rest import duration - >>> request = duration.build_get_null_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestDurationTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_configuration.py deleted file mode 100644 index 029a04192bc..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestDurationTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestDurationTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestDurationTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestdurationtestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/duration/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/duration/__init__.py deleted file mode 100644 index 920665f48c7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/duration/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_null_request -from ._request_builders import build_put_positive_duration_request -from ._request_builders import build_get_positive_duration_request -from ._request_builders import build_get_invalid_request - -__all__ = [ - "build_get_null_request", - "build_put_positive_duration_request", - "build_get_positive_duration_request", - "build_get_invalid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/duration/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/duration/_request_builders.py deleted file mode 100644 index e178029cc3a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/bodydurationlowlevel/rest/duration/_request_builders.py +++ /dev/null @@ -1,122 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null duration value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/duration/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_positive_duration_request(*, json: datetime.timedelta, **kwargs: Any) -> HttpRequest: - """Put a positive duration value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: duration body. Required. - :paramtype json: ~datetime.timedelta - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/duration/positiveduration" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_positive_duration_request(**kwargs: Any) -> HttpRequest: - """Get a positive duration value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/duration/positiveduration" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_request(**kwargs: Any) -> HttpRequest: - """Get an invalid duration value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/duration/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/setup.py deleted file mode 100644 index 0030e99261a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyDurationLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestdurationtestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestDurationTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/__init__.py deleted file mode 100644 index f93513b453c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATFileService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATFileService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_client.py deleted file mode 100644 index 938cd4e9b24..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestSwaggerBATFileServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATFileService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATFileServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodyfilelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodyfilelowlevel.rest import files - >>> request = files.build_get_file_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestSwaggerBATFileService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_configuration.py deleted file mode 100644 index 9fe80719315..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestSwaggerBATFileServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATFileService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATFileServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatfileservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/__init__.py deleted file mode 100644 index bb43be09e1e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATFileService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATFileService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_client.py deleted file mode 100644 index b1c9bd1f11e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestSwaggerBATFileServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATFileService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATFileServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodyfilelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodyfilelowlevel.rest import files - >>> request = files.build_get_file_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestSwaggerBATFileService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_configuration.py deleted file mode 100644 index 4ae048a7d95..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestSwaggerBATFileServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATFileService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATFileServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatfileservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/files/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/files/__init__.py deleted file mode 100644 index 528eba3ed70..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/files/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_file_request -from ._request_builders import build_get_file_large_request -from ._request_builders import build_get_empty_file_request - -__all__ = [ - "build_get_file_request", - "build_get_file_large_request", - "build_get_empty_file_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/files/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/files/_request_builders.py deleted file mode 100644 index c3c1b2b1177..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/bodyfilelowlevel/rest/files/_request_builders.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_file_request(**kwargs: Any) -> HttpRequest: - """Get file. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "image/png, application/json") - - # Construct URL - _url = "/files/stream/nonempty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_file_large_request(**kwargs: Any) -> HttpRequest: - """Get a large file. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "image/png, application/json") - - # Construct URL - _url = "/files/stream/verylarge" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_empty_file_request(**kwargs: Any) -> HttpRequest: - """Get empty file. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "image/png, application/json") - - # Construct URL - _url = "/files/stream/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/setup.py deleted file mode 100644 index a455ac719c1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFileLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestswaggerbatfileservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestSwaggerBATFileService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest Swagger BAT. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/__init__.py deleted file mode 100644 index 0691a18077a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATFormDataService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATFormDataService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_client.py deleted file mode 100644 index f0bbee8a851..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestSwaggerBATFormDataServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATFormDataService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATFormDataServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodyformdatalowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodyformdatalowlevel.rest import formdata - >>> request = formdata.build_upload_file_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestSwaggerBATFormDataService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_configuration.py deleted file mode 100644 index a1bbac2fc1b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestSwaggerBATFormDataServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATFormDataService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATFormDataServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatformdataservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/__init__.py deleted file mode 100644 index 9c0d7799b81..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATFormDataService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATFormDataService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_client.py deleted file mode 100644 index ec68990c20d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestSwaggerBATFormDataServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATFormDataService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATFormDataServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodyformdatalowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodyformdatalowlevel.rest import formdata - >>> request = formdata.build_upload_file_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestSwaggerBATFormDataService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_configuration.py deleted file mode 100644 index c5eef4f228c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestSwaggerBATFormDataServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATFormDataService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATFormDataServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatformdataservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/formdata/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/formdata/__init__.py deleted file mode 100644 index 88403b5aa98..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/formdata/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_upload_file_request -from ._request_builders import build_upload_file_via_body_request -from ._request_builders import build_upload_files_request - -__all__ = [ - "build_upload_file_request", - "build_upload_file_via_body_request", - "build_upload_files_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/formdata/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/formdata/_request_builders.py deleted file mode 100644 index 509c5fce2a6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/bodyformdatalowlevel/rest/formdata/_request_builders.py +++ /dev/null @@ -1,118 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, IO, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_upload_file_request(**kwargs: Any) -> HttpRequest: - """Upload file. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - files = { - "str": {} # Optional. - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/octet-stream, application/json") - - # Construct URL - _url = "/formdata/stream/uploadfile" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_upload_file_via_body_request(*, content: IO, **kwargs: Any) -> HttpRequest: - """Upload file. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: File to upload. Required. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/octet-stream, application/json") - - # Construct URL - _url = "/formdata/stream/uploadfile" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_upload_files_request(**kwargs: Any) -> HttpRequest: - """Upload multiple files. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - files = { - "str": {} # Optional. - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/octet-stream, application/json") - - # Construct URL - _url = "/formdata/stream/uploadfiles" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/setup.py deleted file mode 100644 index 5067a849ab9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormDataLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestswaggerbatformdataservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestSwaggerBATFormDataService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest Swagger BAT. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/__init__.py deleted file mode 100644 index 296b94fa68a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import BodyFormsDataURLEncoded -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["BodyFormsDataURLEncoded"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_client.py deleted file mode 100644 index d9468e71a20..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import BodyFormsDataURLEncodedConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class BodyFormsDataURLEncoded: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = BodyFormsDataURLEncodedConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodyformurlencodeddatalowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodyformurlencodeddatalowlevel.rest import formdataurlencoded - >>> request = formdataurlencoded.build_update_pet_with_form_request(pet_id, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> BodyFormsDataURLEncoded - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_configuration.py deleted file mode 100644 index 38ea6b61030..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class BodyFormsDataURLEncodedConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for BodyFormsDataURLEncoded. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(BodyFormsDataURLEncodedConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "bodyformsdataurlencoded/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_vendor.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/__init__.py deleted file mode 100644 index 1b3a139a318..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import BodyFormsDataURLEncoded - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["BodyFormsDataURLEncoded"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_client.py deleted file mode 100644 index 3d3b29c1242..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import BodyFormsDataURLEncodedConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class BodyFormsDataURLEncoded: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = BodyFormsDataURLEncodedConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodyformurlencodeddatalowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodyformurlencodeddatalowlevel.rest import formdataurlencoded - >>> request = formdataurlencoded.build_update_pet_with_form_request(pet_id, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "BodyFormsDataURLEncoded": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_configuration.py deleted file mode 100644 index 60d34b8149c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class BodyFormsDataURLEncodedConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for BodyFormsDataURLEncoded. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(BodyFormsDataURLEncodedConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "bodyformsdataurlencoded/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/formdataurlencoded/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/formdataurlencoded/__init__.py deleted file mode 100644 index bfaf39986c5..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/formdataurlencoded/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_update_pet_with_form_request -from ._request_builders import build_partial_constant_body_request - -__all__ = [ - "build_update_pet_with_form_request", - "build_partial_constant_body_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/formdataurlencoded/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/formdataurlencoded/_request_builders.py deleted file mode 100644 index b8e1fc04127..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/bodyformurlencodeddatalowlevel/rest/formdataurlencoded/_request_builders.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_update_pet_with_form_request(pet_id: int, **kwargs: Any) -> HttpRequest: - """Updates a pet in the store with form data. - - Updates a pet in the store with form data. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param pet_id: ID of pet that needs to be updated. Required. - :type pet_id: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - data = { - "str": {} # Optional. - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/formsdataurlencoded/pet/add/{petId}" - path_format_arguments = { - "petId": _SERIALIZER.url("pet_id", pet_id, "int"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_partial_constant_body_request(**kwargs: Any) -> HttpRequest: - """Test a partially constant formdata body. Pass in { grant_type: 'access_token', access_token: - 'foo', service: 'bar' } to pass the test. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - data = { - "str": {} # Optional. - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/formsdataurlencoded/partialConstantBody" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/setup.py deleted file mode 100644 index ae9a0ac53a5..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "bodyformsdataurlencoded" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="BodyFormsDataURLEncoded", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest Swagger BAT. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/__init__.py deleted file mode 100644 index 96b9464156d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestIntegerTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestIntegerTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_client.py deleted file mode 100644 index d1820e74f76..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestIntegerTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestIntegerTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestIntegerTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodyintegerlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodyintegerlowlevel.rest import int - >>> request = int.build_get_null_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestIntegerTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_configuration.py deleted file mode 100644 index b87ccec77bd..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestIntegerTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestIntegerTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestIntegerTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestintegertestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/__init__.py deleted file mode 100644 index dc64c6679c1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestIntegerTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestIntegerTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_client.py deleted file mode 100644 index 0e1a7fca538..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestIntegerTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestIntegerTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestIntegerTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodyintegerlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodyintegerlowlevel.rest import int - >>> request = int.build_get_null_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestIntegerTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_configuration.py deleted file mode 100644 index 5a760bb48ef..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestIntegerTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestIntegerTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestIntegerTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestintegertestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/int/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/int/__init__.py deleted file mode 100644 index 3bf0224cb44..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/int/__init__.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_null_request -from ._request_builders import build_get_invalid_request -from ._request_builders import build_get_overflow_int32_request -from ._request_builders import build_get_underflow_int32_request -from ._request_builders import build_get_overflow_int64_request -from ._request_builders import build_get_underflow_int64_request -from ._request_builders import build_put_max32_request -from ._request_builders import build_put_max64_request -from ._request_builders import build_put_min32_request -from ._request_builders import build_put_min64_request -from ._request_builders import build_get_unix_time_request -from ._request_builders import build_put_unix_time_date_request -from ._request_builders import build_get_invalid_unix_time_request -from ._request_builders import build_get_null_unix_time_request - -__all__ = [ - "build_get_null_request", - "build_get_invalid_request", - "build_get_overflow_int32_request", - "build_get_underflow_int32_request", - "build_get_overflow_int64_request", - "build_get_underflow_int64_request", - "build_put_max32_request", - "build_put_max64_request", - "build_put_min32_request", - "build_put_min64_request", - "build_get_unix_time_request", - "build_put_unix_time_date_request", - "build_get_invalid_unix_time_request", - "build_get_null_unix_time_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/int/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/int/_request_builders.py deleted file mode 100644 index 2a5b438a90b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/bodyintegerlowlevel/rest/int/_request_builders.py +++ /dev/null @@ -1,392 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null Int value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_request(**kwargs: Any) -> HttpRequest: - """Get invalid Int value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_overflow_int32_request(**kwargs: Any) -> HttpRequest: - """Get overflow Int32 value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/overflowint32" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_underflow_int32_request(**kwargs: Any) -> HttpRequest: - """Get underflow Int32 value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/underflowint32" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_overflow_int64_request(**kwargs: Any) -> HttpRequest: - """Get overflow Int64 value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/overflowint64" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_underflow_int64_request(**kwargs: Any) -> HttpRequest: - """Get underflow Int64 value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/underflowint64" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_max32_request(*, json: int, **kwargs: Any) -> HttpRequest: - """Put max int32 value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: int body. Required. - :paramtype json: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/max/32" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_put_max64_request(*, json: int, **kwargs: Any) -> HttpRequest: - """Put max int64 value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: int body. Required. - :paramtype json: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/max/64" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_put_min32_request(*, json: int, **kwargs: Any) -> HttpRequest: - """Put min int32 value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: int body. Required. - :paramtype json: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/min/32" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_put_min64_request(*, json: int, **kwargs: Any) -> HttpRequest: - """Put min int64 value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: int body. Required. - :paramtype json: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/min/64" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_unix_time_request(**kwargs: Any) -> HttpRequest: - """Get datetime encoded as Unix time value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/unixtime" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_unix_time_date_request(*, json: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Put datetime encoded as Unix time. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: int body. Required. - :paramtype json: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/unixtime" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_invalid_unix_time_request(**kwargs: Any) -> HttpRequest: - """Get invalid Unix time value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/invalidunixtime" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_null_unix_time_request(**kwargs: Any) -> HttpRequest: - """Get null Unix time value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/int/nullunixtime" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/setup.py deleted file mode 100644 index a0c72dfdd1b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyIntegerLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestintegertestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestIntegerTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/__init__.py deleted file mode 100644 index b8d7d3d1ac9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestNumberTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestNumberTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_client.py deleted file mode 100644 index 7ebbf2e4fcf..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestNumberTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestNumberTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestNumberTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodynumberlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodynumberlowlevel.rest import number - >>> request = number.build_get_null_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestNumberTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_configuration.py deleted file mode 100644 index 06b75f515c1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestNumberTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestNumberTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestNumberTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestnumbertestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/__init__.py deleted file mode 100644 index 1b1608fc7b6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestNumberTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestNumberTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_client.py deleted file mode 100644 index 01b1c77419a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestNumberTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestNumberTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestNumberTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodynumberlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodynumberlowlevel.rest import number - >>> request = number.build_get_null_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestNumberTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_configuration.py deleted file mode 100644 index 40dac1b308b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestNumberTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestNumberTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestNumberTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestnumbertestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/number/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/number/__init__.py deleted file mode 100644 index b658424d6e8..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/number/__init__.py +++ /dev/null @@ -1,59 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_null_request -from ._request_builders import build_get_invalid_float_request -from ._request_builders import build_get_invalid_double_request -from ._request_builders import build_get_invalid_decimal_request -from ._request_builders import build_put_big_float_request -from ._request_builders import build_get_big_float_request -from ._request_builders import build_put_big_double_request -from ._request_builders import build_get_big_double_request -from ._request_builders import build_put_big_double_positive_decimal_request -from ._request_builders import build_get_big_double_positive_decimal_request -from ._request_builders import build_put_big_double_negative_decimal_request -from ._request_builders import build_get_big_double_negative_decimal_request -from ._request_builders import build_put_big_decimal_request -from ._request_builders import build_get_big_decimal_request -from ._request_builders import build_put_big_decimal_positive_decimal_request -from ._request_builders import build_get_big_decimal_positive_decimal_request -from ._request_builders import build_put_big_decimal_negative_decimal_request -from ._request_builders import build_get_big_decimal_negative_decimal_request -from ._request_builders import build_put_small_float_request -from ._request_builders import build_get_small_float_request -from ._request_builders import build_put_small_double_request -from ._request_builders import build_get_small_double_request -from ._request_builders import build_put_small_decimal_request -from ._request_builders import build_get_small_decimal_request - -__all__ = [ - "build_get_null_request", - "build_get_invalid_float_request", - "build_get_invalid_double_request", - "build_get_invalid_decimal_request", - "build_put_big_float_request", - "build_get_big_float_request", - "build_put_big_double_request", - "build_get_big_double_request", - "build_put_big_double_positive_decimal_request", - "build_get_big_double_positive_decimal_request", - "build_put_big_double_negative_decimal_request", - "build_get_big_double_negative_decimal_request", - "build_put_big_decimal_request", - "build_get_big_decimal_request", - "build_put_big_decimal_positive_decimal_request", - "build_get_big_decimal_positive_decimal_request", - "build_put_big_decimal_negative_decimal_request", - "build_get_big_decimal_negative_decimal_request", - "build_put_small_float_request", - "build_get_small_float_request", - "build_put_small_double_request", - "build_get_small_double_request", - "build_put_small_decimal_request", - "build_get_small_decimal_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/number/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/number/_request_builders.py deleted file mode 100644 index 35a8f839205..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/bodynumberlowlevel/rest/number/_request_builders.py +++ /dev/null @@ -1,674 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null Number value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_float_request(**kwargs: Any) -> HttpRequest: - """Get invalid float Number value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/invalidfloat" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_double_request(**kwargs: Any) -> HttpRequest: - """Get invalid double Number value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/invaliddouble" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_invalid_decimal_request(**kwargs: Any) -> HttpRequest: - """Get invalid decimal Number value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/invaliddecimal" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_big_float_request(*, json: float, **kwargs: Any) -> HttpRequest: - """Put big float value 3.402823e+20. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: number body. Required. - :paramtype json: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/float/3.402823e+20" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_big_float_request(**kwargs: Any) -> HttpRequest: - """Get big float value 3.402823e+20. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/float/3.402823e+20" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_big_double_request(*, json: float, **kwargs: Any) -> HttpRequest: - """Put big double value 2.5976931e+101. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: number body. Required. - :paramtype json: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/double/2.5976931e+101" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_big_double_request(**kwargs: Any) -> HttpRequest: - """Get big double value 2.5976931e+101. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/double/2.5976931e+101" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_big_double_positive_decimal_request(**kwargs: Any) -> HttpRequest: - """Put big double value 99999999.99. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Default value is 99999999.99. Note that overriding this default value may result - in unsupported behavior. - :paramtype json: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - json = kwargs.pop("json", 99999999.99) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/double/99999999.99" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_big_double_positive_decimal_request(**kwargs: Any) -> HttpRequest: - """Get big double value 99999999.99. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/double/99999999.99" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_big_double_negative_decimal_request(**kwargs: Any) -> HttpRequest: - """Put big double value -99999999.99. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Default value is -99999999.99. Note that overriding this default value may - result in unsupported behavior. - :paramtype json: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - json = kwargs.pop("json", -99999999.99) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/double/-99999999.99" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_big_double_negative_decimal_request(**kwargs: Any) -> HttpRequest: - """Get big double value -99999999.99. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/double/-99999999.99" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_big_decimal_request(*, json: float, **kwargs: Any) -> HttpRequest: - """Put big decimal value 2.5976931e+101. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: number body. Required. - :paramtype json: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/decimal/2.5976931e+101" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_big_decimal_request(**kwargs: Any) -> HttpRequest: - """Get big decimal value 2.5976931e+101. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/decimal/2.5976931e+101" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_big_decimal_positive_decimal_request(**kwargs: Any) -> HttpRequest: - """Put big decimal value 99999999.99. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Default value is 99999999.99. Note that overriding this default value may result - in unsupported behavior. - :paramtype json: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - json = kwargs.pop("json", 99999999.99) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/decimal/99999999.99" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_big_decimal_positive_decimal_request(**kwargs: Any) -> HttpRequest: - """Get big decimal value 99999999.99. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/decimal/99999999.99" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_big_decimal_negative_decimal_request(**kwargs: Any) -> HttpRequest: - """Put big decimal value -99999999.99. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Default value is -99999999.99. Note that overriding this default value may - result in unsupported behavior. - :paramtype json: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - json = kwargs.pop("json", -99999999.99) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/decimal/-99999999.99" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_big_decimal_negative_decimal_request(**kwargs: Any) -> HttpRequest: - """Get big decimal value -99999999.99. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/big/decimal/-99999999.99" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_small_float_request(*, json: float, **kwargs: Any) -> HttpRequest: - """Put small float value 3.402823e-20. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: number body. Required. - :paramtype json: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/small/float/3.402823e-20" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_small_float_request(**kwargs: Any) -> HttpRequest: - """Get big double value 3.402823e-20. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/small/float/3.402823e-20" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_small_double_request(*, json: float, **kwargs: Any) -> HttpRequest: - """Put small double value 2.5976931e-101. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: number body. Required. - :paramtype json: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/small/double/2.5976931e-101" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_small_double_request(**kwargs: Any) -> HttpRequest: - """Get big double value 2.5976931e-101. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/small/double/2.5976931e-101" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_small_decimal_request(*, json: float, **kwargs: Any) -> HttpRequest: - """Put small decimal value 2.5976931e-101. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: number body. Required. - :paramtype json: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/small/decimal/2.5976931e-101" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_small_decimal_request(**kwargs: Any) -> HttpRequest: - """Get small decimal value 2.5976931e-101. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/number/small/decimal/2.5976931e-101" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/setup.py deleted file mode 100644 index f2b6ded60ea..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyNumberLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestnumbertestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestNumberTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/__init__.py deleted file mode 100644 index d75cfe0c216..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_client.py deleted file mode 100644 index 5396fdf7408..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestSwaggerBATServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodystringlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodystringlowlevel.rest import string - >>> request = string.build_get_null_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestSwaggerBATService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_configuration.py deleted file mode 100644 index 1239968e001..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestSwaggerBATServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/__init__.py deleted file mode 100644 index 6ee482870d4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_client.py deleted file mode 100644 index 00698b653d3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestSwaggerBATServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodystringlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodystringlowlevel.rest import string - >>> request = string.build_get_null_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestSwaggerBATService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_configuration.py deleted file mode 100644 index 9f14e32ca57..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestSwaggerBATServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/enum/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/enum/__init__.py deleted file mode 100644 index ec2a8a0642c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/enum/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_not_expandable_request -from ._request_builders import build_put_not_expandable_request -from ._request_builders import build_get_referenced_request -from ._request_builders import build_put_referenced_request -from ._request_builders import build_get_referenced_constant_request -from ._request_builders import build_put_referenced_constant_request - -__all__ = [ - "build_get_not_expandable_request", - "build_put_not_expandable_request", - "build_get_referenced_request", - "build_put_referenced_request", - "build_get_referenced_constant_request", - "build_put_referenced_constant_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/enum/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/enum/_request_builders.py deleted file mode 100644 index 556e5a91784..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/enum/_request_builders.py +++ /dev/null @@ -1,245 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_not_expandable_request(**kwargs: Any) -> HttpRequest: - """Get enum value 'red color' from enumeration of 'red color', 'green-color', 'blue_color'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/enum/notExpandable" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_not_expandable_request(*, json: str, **kwargs: Any) -> HttpRequest: - """Sends value 'red color' from enumeration of 'red color', 'green-color', 'blue_color'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: string body. Known values are: "red color", "green-color", and "blue_color". - Required. - :paramtype json: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/enum/notExpandable" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_referenced_request(**kwargs: Any) -> HttpRequest: - """Get enum value 'red color' from enumeration of 'red color', 'green-color', 'blue_color'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/enum/Referenced" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_referenced_request(*, json: str, **kwargs: Any) -> HttpRequest: - """Sends value 'red color' from enumeration of 'red color', 'green-color', 'blue_color'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: enum string body. Known values are: "red color", "green-color", and - "blue_color". Required. - :paramtype json: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/enum/Referenced" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_referenced_constant_request(**kwargs: Any) -> HttpRequest: - """Get value 'green-color' from the constant. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/enum/ReferencedConstant" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_referenced_constant_request( - *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Sends value 'green-color' from a constant. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: enum string body. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "ColorConstant": "green-color", # Default value is "green-color". Referenced - Color Constant Description. Required. - "field1": "str" # Optional. Sample string. - } - """ - - -@overload -def build_put_referenced_constant_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Sends value 'green-color' from a constant. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: enum string body. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_referenced_constant_request(**kwargs: Any) -> HttpRequest: - """Sends value 'green-color' from a constant. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: enum string body. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/enum/ReferencedConstant" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/string/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/string/__init__.py deleted file mode 100644 index a204e22cefd..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/string/__init__.py +++ /dev/null @@ -1,37 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_null_request -from ._request_builders import build_put_null_request -from ._request_builders import build_get_empty_request -from ._request_builders import build_put_empty_request -from ._request_builders import build_get_mbcs_request -from ._request_builders import build_put_mbcs_request -from ._request_builders import build_get_whitespace_request -from ._request_builders import build_put_whitespace_request -from ._request_builders import build_get_not_provided_request -from ._request_builders import build_get_base64_encoded_request -from ._request_builders import build_get_base64_url_encoded_request -from ._request_builders import build_put_base64_url_encoded_request -from ._request_builders import build_get_null_base64_url_encoded_request - -__all__ = [ - "build_get_null_request", - "build_put_null_request", - "build_get_empty_request", - "build_put_empty_request", - "build_get_mbcs_request", - "build_put_mbcs_request", - "build_get_whitespace_request", - "build_put_whitespace_request", - "build_get_not_provided_request", - "build_get_base64_encoded_request", - "build_get_base64_url_encoded_request", - "build_put_base64_url_encoded_request", - "build_get_null_base64_url_encoded_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/string/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/string/_request_builders.py deleted file mode 100644 index 398cc27a6b6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/bodystringlowlevel/rest/string/_request_builders.py +++ /dev/null @@ -1,380 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_null_request(**kwargs: Any) -> HttpRequest: - """Get null string value value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/null" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_null_request(*, content: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Set string value null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: string body. Default value is None. - :paramtype content: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/null" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_empty_request(**kwargs: Any) -> HttpRequest: - """Get empty string value value ''. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_empty_request(**kwargs: Any) -> HttpRequest: - """Set string value empty ''. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: string body. Required. Default value is "". Note that overriding this default - value may result in unsupported behavior. - :paramtype json: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - json = kwargs.pop("json", "") # type: str - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/empty" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_mbcs_request(**kwargs: Any) -> HttpRequest: - """Get mbcs string value '啊齄丂狛狜隣郎隣兀﨩ˊ〞〡¦℡㈱‐ー﹡﹢﹫、〓ⅰⅹ⒈€㈠㈩ⅠⅫ! ̄ぁんァヶΑ︴АЯаяāɡㄅㄩ─╋︵﹄︻︱︳︴ⅰⅹɑɡ〇〾⿻⺁䜣€'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/mbcs" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_mbcs_request(**kwargs: Any) -> HttpRequest: - """Set string value mbcs '啊齄丂狛狜隣郎隣兀﨩ˊ〞〡¦℡㈱‐ー﹡﹢﹫、〓ⅰⅹ⒈€㈠㈩ⅠⅫ! ̄ぁんァヶΑ︴АЯаяāɡㄅㄩ─╋︵﹄︻︱︳︴ⅰⅹɑɡ〇〾⿻⺁䜣€'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: string body. Default value is - "啊齄丂狛狜隣郎隣兀﨩ˊ〞〡¦℡㈱‐ー﹡﹢﹫、〓ⅰⅹ⒈€㈠㈩ⅠⅫ! ̄ぁんァヶΑ︴АЯаяāɡㄅㄩ─╋︵﹄︻︱︳︴ⅰⅹɑɡ〇〾⿻⺁䜣€". Note that overriding - this default value may result in unsupported behavior. - :paramtype json: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - json = kwargs.pop("json", "啊齄丂狛狜隣郎隣兀﨩ˊ〞〡¦℡㈱‐ー﹡﹢﹫、〓ⅰⅹ⒈€㈠㈩ⅠⅫ! ̄ぁんァヶΑ︴АЯаяāɡㄅㄩ─╋︵﹄︻︱︳︴ⅰⅹɑɡ〇〾⿻⺁䜣€") # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/mbcs" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_whitespace_request(**kwargs: Any) -> HttpRequest: - """Get string value with leading and trailing whitespace - ':code:``:code:``:code:``Now is the time for all good men to come to the aid - of their country:code:``:code:``:code:``'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/whitespace" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_whitespace_request(**kwargs: Any) -> HttpRequest: - """Set String value with leading and trailing whitespace - ':code:``:code:``:code:``Now is the time for all good men to come to the aid - of their country:code:``:code:``:code:``'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: string body. Default value is " Now is the time for all good men to come to - the aid of their country ". Note that overriding this default value may result in - unsupported behavior. - :paramtype json: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - json = kwargs.pop( - "json", " Now is the time for all good men to come to the aid of their country " - ) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/whitespace" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_not_provided_request(**kwargs: Any) -> HttpRequest: - """Get String value when no string value is sent in response payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/notProvided" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_base64_encoded_request(**kwargs: Any) -> HttpRequest: - """Get value that is base64 encoded. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/base64Encoding" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_base64_url_encoded_request(**kwargs: Any) -> HttpRequest: - """Get value that is base64url encoded. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/base64UrlEncoding" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_base64_url_encoded_request(*, json: bytes, **kwargs: Any) -> HttpRequest: - """Put value that is base64url encoded. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: string body. Required. - :paramtype json: bytes - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/base64UrlEncoding" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_null_base64_url_encoded_request(**kwargs: Any) -> HttpRequest: - """Get null value that is expected to be base64url encoded. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/string/nullBase64UrlEncoding" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/setup.py deleted file mode 100644 index 1b5d0e8b09a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyStringLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestswaggerbatservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestSwaggerBATService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest Swagger BAT. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/__init__.py deleted file mode 100644 index ce94799ff86..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestTimeTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestTimeTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_client.py deleted file mode 100644 index d8e87be7c30..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestTimeTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestTimeTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestTimeTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodytimelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodytimelowlevel.rest import time - >>> request = time.build_get_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestTimeTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_configuration.py deleted file mode 100644 index 92c452e95b6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestTimeTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestTimeTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestTimeTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autoresttimetestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/__init__.py deleted file mode 100644 index 6c3f154a912..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestTimeTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestTimeTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_client.py deleted file mode 100644 index d70622b7e93..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestTimeTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestTimeTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestTimeTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `bodytimelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from bodytimelowlevel.rest import time - >>> request = time.build_get_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestTimeTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_configuration.py deleted file mode 100644 index 4cc72dc2ebf..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestTimeTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestTimeTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestTimeTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autoresttimetestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/time/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/time/__init__.py deleted file mode 100644 index 5c0124f9ae3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/time/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_request -from ._request_builders import build_put_request - -__all__ = [ - "build_get_request", - "build_put_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/time/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/time/_request_builders.py deleted file mode 100644 index ae52ed2e547..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/bodytimelowlevel/rest/time/_request_builders.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_request(**kwargs: Any) -> HttpRequest: - """Get time value "11:34:56". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/time/get" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_request(*, json: datetime.time, **kwargs: Any) -> HttpRequest: - """Put time value "08:07:56". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Put time value "08:07:56" in parameter to pass testserver. Required. - :paramtype json: ~datetime.time - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/time/put" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/setup.py deleted file mode 100644 index 0cf626a3e41..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/BodyTimeLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autoresttimetestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestTimeTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/__init__.py deleted file mode 100644 index 8cb9c33ad70..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerConstantService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerConstantService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_client.py deleted file mode 100644 index e0c84908614..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_client.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestSwaggerConstantServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerConstantService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger Constant. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - :keyword header_constant: Constant header property on the client that is a required parameter - for operation 'constants_putClientConstants'. Default value is True. Note that overriding this - default value may result in unsupported behavior. - :paramtype header_constant: bool - :keyword query_constant: Constant query property on the client that is a required parameter for - operation 'constants_putClientConstants'. Default value is 100. Note that overriding this - default value may result in unsupported behavior. - :paramtype query_constant: int - :keyword path_constant: Constant path property on the client that is a required parameter for - operation 'constants_putClientConstants'. Default value is "path". Note that overriding this - default value may result in unsupported behavior. - :paramtype path_constant: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerConstantServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `constantslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from constantslowlevel.rest import contants - >>> request = contants.build_put_no_model_as_string_no_required_two_value_no_default_request(input=input, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestSwaggerConstantService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_configuration.py deleted file mode 100644 index dd7727ddaa2..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_configuration.py +++ /dev/null @@ -1,61 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestSwaggerConstantServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerConstantService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :keyword header_constant: Constant header property on the client that is a required parameter - for operation 'constants_putClientConstants'. Default value is True. Note that overriding this - default value may result in unsupported behavior. - :paramtype header_constant: bool - :keyword query_constant: Constant query property on the client that is a required parameter for - operation 'constants_putClientConstants'. Default value is 100. Note that overriding this - default value may result in unsupported behavior. - :paramtype query_constant: int - :keyword path_constant: Constant path property on the client that is a required parameter for - operation 'constants_putClientConstants'. Default value is "path". Note that overriding this - default value may result in unsupported behavior. - :paramtype path_constant: str - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerConstantServiceConfiguration, self).__init__(**kwargs) - header_constant = kwargs.pop("header_constant", True) # type: bool - query_constant = kwargs.pop("query_constant", 100) # type: int - path_constant = kwargs.pop("path_constant", "path") # type: str - - self.header_constant = header_constant - self.query_constant = query_constant - self.path_constant = path_constant - kwargs.setdefault("sdk_moniker", "autorestswaggerconstantservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_vendor.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/__init__.py deleted file mode 100644 index 7931f8a59d4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerConstantService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerConstantService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_client.py deleted file mode 100644 index 6a85e0d1b65..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_client.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestSwaggerConstantServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerConstantService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger Constant. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - :keyword header_constant: Constant header property on the client that is a required parameter - for operation 'constants_putClientConstants'. Default value is True. Note that overriding this - default value may result in unsupported behavior. - :paramtype header_constant: bool - :keyword query_constant: Constant query property on the client that is a required parameter for - operation 'constants_putClientConstants'. Default value is 100. Note that overriding this - default value may result in unsupported behavior. - :paramtype query_constant: int - :keyword path_constant: Constant path property on the client that is a required parameter for - operation 'constants_putClientConstants'. Default value is "path". Note that overriding this - default value may result in unsupported behavior. - :paramtype path_constant: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerConstantServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `constantslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from constantslowlevel.rest import contants - >>> request = contants.build_put_no_model_as_string_no_required_two_value_no_default_request(input=input, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestSwaggerConstantService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_configuration.py deleted file mode 100644 index 3ae7b878d99..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_configuration.py +++ /dev/null @@ -1,58 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestSwaggerConstantServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerConstantService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :keyword header_constant: Constant header property on the client that is a required parameter - for operation 'constants_putClientConstants'. Default value is True. Note that overriding this - default value may result in unsupported behavior. - :paramtype header_constant: bool - :keyword query_constant: Constant query property on the client that is a required parameter for - operation 'constants_putClientConstants'. Default value is 100. Note that overriding this - default value may result in unsupported behavior. - :paramtype query_constant: int - :keyword path_constant: Constant path property on the client that is a required parameter for - operation 'constants_putClientConstants'. Default value is "path". Note that overriding this - default value may result in unsupported behavior. - :paramtype path_constant: str - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerConstantServiceConfiguration, self).__init__(**kwargs) - header_constant = kwargs.pop("header_constant", True) # type: bool - query_constant = kwargs.pop("query_constant", 100) # type: int - path_constant = kwargs.pop("path_constant", "path") # type: str - - self.header_constant = header_constant - self.query_constant = query_constant - self.path_constant = path_constant - kwargs.setdefault("sdk_moniker", "autorestswaggerconstantservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/contants/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/contants/__init__.py deleted file mode 100644 index 478e47091eb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/contants/__init__.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_put_no_model_as_string_no_required_two_value_no_default_request -from ._request_builders import build_put_no_model_as_string_no_required_two_value_default_request -from ._request_builders import build_put_no_model_as_string_no_required_one_value_no_default_request -from ._request_builders import build_put_no_model_as_string_no_required_one_value_default_request -from ._request_builders import build_put_no_model_as_string_required_two_value_no_default_request -from ._request_builders import build_put_no_model_as_string_required_two_value_default_request -from ._request_builders import build_put_no_model_as_string_required_one_value_no_default_request -from ._request_builders import build_put_no_model_as_string_required_one_value_default_request -from ._request_builders import build_put_model_as_string_no_required_two_value_no_default_request -from ._request_builders import build_put_model_as_string_no_required_two_value_default_request -from ._request_builders import build_put_model_as_string_no_required_one_value_no_default_request -from ._request_builders import build_put_model_as_string_no_required_one_value_default_request -from ._request_builders import build_put_model_as_string_required_two_value_no_default_request -from ._request_builders import build_put_model_as_string_required_two_value_default_request -from ._request_builders import build_put_model_as_string_required_one_value_no_default_request -from ._request_builders import build_put_model_as_string_required_one_value_default_request -from ._request_builders import build_put_client_constants_request - -__all__ = [ - "build_put_no_model_as_string_no_required_two_value_no_default_request", - "build_put_no_model_as_string_no_required_two_value_default_request", - "build_put_no_model_as_string_no_required_one_value_no_default_request", - "build_put_no_model_as_string_no_required_one_value_default_request", - "build_put_no_model_as_string_required_two_value_no_default_request", - "build_put_no_model_as_string_required_two_value_default_request", - "build_put_no_model_as_string_required_one_value_no_default_request", - "build_put_no_model_as_string_required_one_value_default_request", - "build_put_model_as_string_no_required_two_value_no_default_request", - "build_put_model_as_string_no_required_two_value_default_request", - "build_put_model_as_string_no_required_one_value_no_default_request", - "build_put_model_as_string_no_required_one_value_default_request", - "build_put_model_as_string_required_two_value_no_default_request", - "build_put_model_as_string_required_two_value_default_request", - "build_put_model_as_string_required_one_value_no_default_request", - "build_put_model_as_string_required_one_value_default_request", - "build_put_client_constants_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/contants/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/contants/_request_builders.py deleted file mode 100644 index 8bc6db7bfed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/constantslowlevel/rest/contants/_request_builders.py +++ /dev/null @@ -1,531 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_put_no_model_as_string_no_required_two_value_no_default_request( - *, input: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Known values are: "value1" and "value2". Default value is None. - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putNoModelAsStringNoRequiredTwoValueNoDefault" - - # Construct parameters - if input is not None: - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_no_model_as_string_no_required_two_value_default_request( - *, input: str = "value1", **kwargs: Any -) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Known values are: "value1" and "value2". Default value is "value1". - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putNoModelAsStringNoRequiredTwoValueDefault" - - # Construct parameters - if input is not None: - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_no_model_as_string_no_required_one_value_no_default_request( - *, input: str = "value1", **kwargs: Any -) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Known values are "value1" and None. Default value is "value1". - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putNoModelAsStringNoRequiredOneValueNoDefault" - - # Construct parameters - if input is not None: - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_no_model_as_string_no_required_one_value_default_request( - *, input: str = "value1", **kwargs: Any -) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Known values are "value1" and None. Default value is "value1". - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putNoModelAsStringNoRequiredOneValueDefault" - - # Construct parameters - if input is not None: - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_no_model_as_string_required_two_value_no_default_request(*, input: str, **kwargs: Any) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Known values are: "value1" and "value2". Required. - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putNoModelAsStringRequiredTwoValueNoDefault" - - # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_no_model_as_string_required_two_value_default_request( - *, input: str = "value1", **kwargs: Any -) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Known values are: "value1" and "value2". Default value is "value1". - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putNoModelAsStringRequiredTwoValueDefault" - - # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_no_model_as_string_required_one_value_no_default_request(**kwargs: Any) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Default value is "value1". Note that overriding this default value may result - in unsupported behavior. - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - input = kwargs.pop("input", _params.pop("input", "value1")) # type: str - # Construct URL - _url = "/constants/putNoModelAsStringRequiredOneValueNoDefault" - - # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_no_model_as_string_required_one_value_default_request(**kwargs: Any) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Default value is "value1". Note that overriding this default value may result - in unsupported behavior. - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - input = kwargs.pop("input", _params.pop("input", "value1")) # type: str - # Construct URL - _url = "/constants/putNoModelAsStringRequiredOneValueDefault" - - # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_model_as_string_no_required_two_value_no_default_request( - *, input: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Known values are: "value1" and "value2". Default value is None. - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putModelAsStringNoRequiredTwoValueNoDefault" - - # Construct parameters - if input is not None: - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_model_as_string_no_required_two_value_default_request( - *, input: str = "value1", **kwargs: Any -) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Known values are: "value1" and "value2". Default value is "value1". - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putModelAsStringNoRequiredTwoValueDefault" - - # Construct parameters - if input is not None: - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_model_as_string_no_required_one_value_no_default_request( - *, input: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: "value1" Default value is None. - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putModelAsStringNoRequiredOneValueNoDefault" - - # Construct parameters - if input is not None: - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_model_as_string_no_required_one_value_default_request( - *, input: str = "value1", **kwargs: Any -) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: "value1" Default value is "value1". - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putModelAsStringNoRequiredOneValueDefault" - - # Construct parameters - if input is not None: - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_model_as_string_required_two_value_no_default_request(*, input: str, **kwargs: Any) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Known values are: "value1" and "value2". Required. - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putModelAsStringRequiredTwoValueNoDefault" - - # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_model_as_string_required_two_value_default_request( - *, input: str = "value1", **kwargs: Any -) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: Known values are: "value1" and "value2". Default value is "value1". - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putModelAsStringRequiredTwoValueDefault" - - # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_model_as_string_required_one_value_no_default_request(*, input: str, **kwargs: Any) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: "value1" Required. - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putModelAsStringRequiredOneValueNoDefault" - - # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_model_as_string_required_one_value_default_request( - *, input: str = "value1", **kwargs: Any -) -> HttpRequest: - """Puts constants to the testserver. - - Puts constants to the testserver. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword input: "value1" Default value is "value1". - :paramtype input: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - # Construct URL - _url = "/constants/putModelAsStringRequiredOneValueDefault" - - # Construct parameters - _params["input"] = _SERIALIZER.query("input", input, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, **kwargs) - - -def build_put_client_constants_request(**kwargs: Any) -> HttpRequest: - """Pass constants from the client to this function. Will pass in constant path, query, and header - parameters. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword header_constant: Constant header property on the client that is a required parameter - for operation 'constants_putClientConstants'. Default value is True. Note that overriding this - default value may result in unsupported behavior. - :paramtype header_constant: bool - :keyword query_constant: Constant query property on the client that is a required parameter for - operation 'constants_putClientConstants'. Default value is 100. Note that overriding this - default value may result in unsupported behavior. - :paramtype query_constant: int - :keyword path_constant: Constant path property on the client that is a required parameter for - operation 'constants_putClientConstants'. Default value is "path". Note that overriding this - default value may result in unsupported behavior. - :paramtype path_constant: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - header_constant = kwargs.pop("header_constant", _headers.pop("header-constant", True)) # type: bool - query_constant = kwargs.pop("query_constant", _params.pop("query-constant", 100)) # type: int - path_constant = kwargs.pop("path_constant", "path") # type: str - # Construct URL - _url = "/constants/clientConstants/{path-constant}" - path_format_arguments = { - "path-constant": _SERIALIZER.url("path_constant", path_constant, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["query-constant"] = _SERIALIZER.query("query_constant", query_constant, "int") - - # Construct headers - _headers["header-constant"] = _SERIALIZER.header("header_constant", header_constant, "bool") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/setup.py deleted file mode 100644 index 937d4c86cbc..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ConstantsLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestswaggerconstantservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestSwaggerConstantService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest Swagger Constant. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/__init__.py deleted file mode 100644 index 142d64ad945..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterizedHostTestClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterizedHostTestClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_client.py deleted file mode 100644 index 6c01f101c9e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_client.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestParameterizedHostTestClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterizedHostTestClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - _endpoint = "http://{accountName}{host}" - self._config = AutoRestParameterizedHostTestClientConfiguration(host=host, **kwargs) - self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `custombaseurllowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from custombaseurllowlevel.rest import paths - >>> request = paths.build_get_empty_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestParameterizedHostTestClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_configuration.py deleted file mode 100644 index 8b25be0e943..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_configuration.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestParameterizedHostTestClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterizedHostTestClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - super(AutoRestParameterizedHostTestClientConfiguration, self).__init__(**kwargs) - if host is None: - raise ValueError("Parameter 'host' must not be None.") - - self.host = host - kwargs.setdefault("sdk_moniker", "autorestparameterizedhosttestclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/__init__.py deleted file mode 100644 index 5bfa1ff304b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterizedHostTestClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterizedHostTestClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_client.py deleted file mode 100644 index 790c3d1fe85..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_client.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestParameterizedHostTestClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterizedHostTestClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - _endpoint = "http://{accountName}{host}" - self._config = AutoRestParameterizedHostTestClientConfiguration(host=host, **kwargs) - self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `custombaseurllowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from custombaseurllowlevel.rest import paths - >>> request = paths.build_get_empty_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "host": self._serialize.url("self._config.host", self._config.host, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestParameterizedHostTestClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_configuration.py deleted file mode 100644 index e2d2a50345b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_configuration.py +++ /dev/null @@ -1,46 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestParameterizedHostTestClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterizedHostTestClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param host: A string value that is used as a global part of the parameterized host. Default - value is "host". - :type host: str - """ - - def __init__(self, host: str = "host", **kwargs: Any) -> None: - super(AutoRestParameterizedHostTestClientConfiguration, self).__init__(**kwargs) - if host is None: - raise ValueError("Parameter 'host' must not be None.") - - self.host = host - kwargs.setdefault("sdk_moniker", "autorestparameterizedhosttestclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/__init__.py deleted file mode 100644 index b03437179b1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_empty_request - -__all__ = [ - "build_get_empty_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/_request_builders.py deleted file mode 100644 index feca717c807..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/custombaseurllowlevel/rest/paths/_request_builders.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_empty_request(**kwargs: Any) -> HttpRequest: - """Get a 200 to test a valid base uri. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/customuri" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/setup.py deleted file mode 100644 index e4fd12e45ab..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestparameterizedhosttestclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestParameterizedHostTestClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/__init__.py deleted file mode 100644 index 9059c52a7d5..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterizedCustomHostTestClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterizedCustomHostTestClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_client.py deleted file mode 100644 index 29ea24f0118..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_client.py +++ /dev/null @@ -1,86 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestParameterizedCustomHostTestClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterizedCustomHostTestClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param subscription_id: The subscription id with value 'test12'. Required. - :type subscription_id: str - :param dns_suffix: A string value that is used as a global part of the parameterized host. - Default value 'host'. Default value is "host". - :type dns_suffix: str - """ - - def __init__(self, subscription_id: str, dns_suffix: str = "host", **kwargs: Any) -> None: - _endpoint = "{vault}{secret}{dnsSuffix}" - self._config = AutoRestParameterizedCustomHostTestClientConfiguration( - subscription_id=subscription_id, dns_suffix=dns_suffix, **kwargs - ) - self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `custombaseurlmoreoptionslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from custombaseurlmoreoptionslowlevel.rest import paths - >>> request = paths.build_get_empty_request(key_name, subscription_id, key_version=key_version, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "dnsSuffix": self._serialize.url( - "self._config.dns_suffix", self._config.dns_suffix, "str", skip_quote=True - ), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestParameterizedCustomHostTestClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_configuration.py deleted file mode 100644 index 9db4de8e56e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_configuration.py +++ /dev/null @@ -1,56 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestParameterizedCustomHostTestClientConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterizedCustomHostTestClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param subscription_id: The subscription id with value 'test12'. Required. - :type subscription_id: str - :param dns_suffix: A string value that is used as a global part of the parameterized host. - Default value 'host'. Default value is "host". - :type dns_suffix: str - """ - - def __init__(self, subscription_id: str, dns_suffix: str = "host", **kwargs: Any) -> None: - super(AutoRestParameterizedCustomHostTestClientConfiguration, self).__init__(**kwargs) - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - if dns_suffix is None: - raise ValueError("Parameter 'dns_suffix' must not be None.") - - self.subscription_id = subscription_id - self.dns_suffix = dns_suffix - kwargs.setdefault("sdk_moniker", "autorestparameterizedcustomhosttestclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_vendor.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/__init__.py deleted file mode 100644 index 874d0bc010c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterizedCustomHostTestClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterizedCustomHostTestClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_client.py deleted file mode 100644 index 78e81184e32..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_client.py +++ /dev/null @@ -1,83 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestParameterizedCustomHostTestClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterizedCustomHostTestClient: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param subscription_id: The subscription id with value 'test12'. Required. - :type subscription_id: str - :param dns_suffix: A string value that is used as a global part of the parameterized host. - Default value 'host'. Default value is "host". - :type dns_suffix: str - """ - - def __init__(self, subscription_id: str, dns_suffix: str = "host", **kwargs: Any) -> None: - _endpoint = "{vault}{secret}{dnsSuffix}" - self._config = AutoRestParameterizedCustomHostTestClientConfiguration( - subscription_id=subscription_id, dns_suffix=dns_suffix, **kwargs - ) - self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `custombaseurlmoreoptionslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from custombaseurlmoreoptionslowlevel.rest import paths - >>> request = paths.build_get_empty_request(key_name, subscription_id, key_version=key_version, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "dnsSuffix": self._serialize.url( - "self._config.dns_suffix", self._config.dns_suffix, "str", skip_quote=True - ), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestParameterizedCustomHostTestClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_configuration.py deleted file mode 100644 index d126dd72b64..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_configuration.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestParameterizedCustomHostTestClientConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterizedCustomHostTestClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param subscription_id: The subscription id with value 'test12'. Required. - :type subscription_id: str - :param dns_suffix: A string value that is used as a global part of the parameterized host. - Default value 'host'. Default value is "host". - :type dns_suffix: str - """ - - def __init__(self, subscription_id: str, dns_suffix: str = "host", **kwargs: Any) -> None: - super(AutoRestParameterizedCustomHostTestClientConfiguration, self).__init__(**kwargs) - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - if dns_suffix is None: - raise ValueError("Parameter 'dns_suffix' must not be None.") - - self.subscription_id = subscription_id - self.dns_suffix = dns_suffix - kwargs.setdefault("sdk_moniker", "autorestparameterizedcustomhosttestclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/paths/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/paths/__init__.py deleted file mode 100644 index b03437179b1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/paths/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_empty_request - -__all__ = [ - "build_get_empty_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/paths/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/paths/_request_builders.py deleted file mode 100644 index 0aa08a01d41..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/custombaseurlmoreoptionslowlevel/rest/paths/_request_builders.py +++ /dev/null @@ -1,61 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_empty_request( - key_name: str, subscription_id: str, *, key_version: str = "v1", **kwargs: Any -) -> HttpRequest: - """Get a 200 to test a valid base uri. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param key_name: The key name with value 'key1'. Required. - :type key_name: str - :param subscription_id: The subscription id with value 'test12'. Required. - :type subscription_id: str - :keyword key_version: The key version. Default value 'v1'. Default value is "v1". - :paramtype key_version: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/customuri/{subscriptionId}/{keyName}" - path_format_arguments = { - "keyName": _SERIALIZER.url("key_name", key_name, "str"), - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - if key_version is not None: - _params["keyVersion"] = _SERIALIZER.query("key_version", key_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/setup.py deleted file mode 100644 index 54874167d0f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestparameterizedcustomhosttestclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestParameterizedCustomHostTestClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/__init__.py deleted file mode 100644 index dc71f9d0ec6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import ErrorWithSecrets -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["ErrorWithSecrets"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_client.py deleted file mode 100644 index 60282948efa..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import ErrorWithSecretsConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class ErrorWithSecrets: # pylint: disable=client-accepts-api-version-keyword - """Tests whether loggers/tracers redact secrets and PII within error responses. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = ErrorWithSecretsConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `errorwithsecretslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from errorwithsecretslowlevel.rest import build_create_secret_request - >>> request = build_create_secret_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> ErrorWithSecrets - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_configuration.py deleted file mode 100644 index 224f852878d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class ErrorWithSecretsConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for ErrorWithSecrets. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(ErrorWithSecretsConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "errorwithsecrets/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/__init__.py deleted file mode 100644 index 67fc10efe35..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import ErrorWithSecrets - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["ErrorWithSecrets"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_client.py deleted file mode 100644 index 7dc72e4ba3e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import ErrorWithSecretsConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class ErrorWithSecrets: # pylint: disable=client-accepts-api-version-keyword - """Tests whether loggers/tracers redact secrets and PII within error responses. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = ErrorWithSecretsConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `errorwithsecretslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from errorwithsecretslowlevel.rest import build_create_secret_request - >>> request = build_create_secret_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "ErrorWithSecrets": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_configuration.py deleted file mode 100644 index 1994309507d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class ErrorWithSecretsConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for ErrorWithSecrets. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(ErrorWithSecretsConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "errorwithsecrets/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/rest/__init__.py deleted file mode 100644 index 6796b25d19d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/rest/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_create_secret_request -from ._request_builders import build_get_error_with_secrets_request - -__all__ = [ - "build_create_secret_request", - "build_get_error_with_secrets_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/rest/_request_builders.py deleted file mode 100644 index dcd6df0242d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/errorwithsecretslowlevel/rest/_request_builders.py +++ /dev/null @@ -1,66 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_create_secret_request(**kwargs: Any) -> HttpRequest: - """Creates a secret. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/secrets/:create" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_get_error_with_secrets_request(**kwargs: Any) -> HttpRequest: - """Gets an error response containing secrets and PII. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/secrets/error" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/setup.py deleted file mode 100644 index f97510b32d6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ErrorWithSecretsLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "errorwithsecrets" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="ErrorWithSecrets", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Tests whether loggers/tracers redact secrets and PII within error responses. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/__init__.py deleted file mode 100644 index ac220a1e296..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import PetStoreInc -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["PetStoreInc"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_client.py deleted file mode 100644 index ae53c7f3482..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import PetStoreIncConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class PetStoreInc: # pylint: disable=client-accepts-api-version-keyword - """PetStore. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = PetStoreIncConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `extensibleenumsswaggerlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from extensibleenumsswaggerlowlevel.rest import pet - >>> request = pet.build_get_by_pet_id_request(pet_id, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> PetStoreInc - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_configuration.py deleted file mode 100644 index 98dc7e482c5..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class PetStoreIncConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for PetStoreInc. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(PetStoreIncConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "petstoreinc/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_vendor.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/__init__.py deleted file mode 100644 index 3c4c613cf11..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import PetStoreInc - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["PetStoreInc"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_client.py deleted file mode 100644 index 07dae084e41..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import PetStoreIncConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class PetStoreInc: # pylint: disable=client-accepts-api-version-keyword - """PetStore. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = PetStoreIncConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `extensibleenumsswaggerlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from extensibleenumsswaggerlowlevel.rest import pet - >>> request = pet.build_get_by_pet_id_request(pet_id, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "PetStoreInc": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_configuration.py deleted file mode 100644 index dbcf37bdcd3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class PetStoreIncConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for PetStoreInc. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(PetStoreIncConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "petstoreinc/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/pet/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/pet/__init__.py deleted file mode 100644 index 934eaebadd4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/pet/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_by_pet_id_request -from ._request_builders import build_add_pet_request - -__all__ = [ - "build_get_by_pet_id_request", - "build_add_pet_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/pet/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/pet/_request_builders.py deleted file mode 100644 index e67539a46fd..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/extensibleenumsswaggerlowlevel/rest/pet/_request_builders.py +++ /dev/null @@ -1,143 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_by_pet_id_request(pet_id: str, **kwargs: Any) -> HttpRequest: - """get pet by id. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param pet_id: Pet id. Required. - :type pet_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/extensibleenums/pet/{petId}" - path_format_arguments = { - "petId": _SERIALIZER.url("pet_id", pet_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_add_pet_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """add pet. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: pet param. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "DaysOfWeek": "Friday", # Optional. Default value is "Friday". Type of Pet. - Known values are: "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", - "Saturday", and "Sunday". - "IntEnum": "str", # Required. Known values are: "1", "2", and "3". - "name": "str" # Optional. name. - } - """ - - -@overload -def build_add_pet_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """add pet. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: pet param. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_add_pet_request(**kwargs: Any) -> HttpRequest: - """add pet. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: pet param. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/extensibleenums/pet/addPet" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/setup.py deleted file mode 100644 index 466a05a5584..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ExtensibleEnumsLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "petstoreinc" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="PetStoreInc", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - PetStore. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/__init__.py deleted file mode 100644 index 392f9e86fca..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATHeaderService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATHeaderService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_client.py deleted file mode 100644 index fca5c48a604..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestSwaggerBATHeaderServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATHeaderService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATHeaderServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `headerlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from headerlowlevel.rest import header - >>> request = header.build_param_existing_key_request(user_agent_parameter=user_agent_parameter, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestSwaggerBATHeaderService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_configuration.py deleted file mode 100644 index fefd719aa05..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestSwaggerBATHeaderServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATHeaderService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATHeaderServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatheaderservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/__init__.py deleted file mode 100644 index 1e2a85e38a9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATHeaderService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATHeaderService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_client.py deleted file mode 100644 index b783c349648..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestSwaggerBATHeaderServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATHeaderService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATHeaderServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `headerlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from headerlowlevel.rest import header - >>> request = header.build_param_existing_key_request(user_agent_parameter=user_agent_parameter, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestSwaggerBATHeaderService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_configuration.py deleted file mode 100644 index 04c790d0397..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestSwaggerBATHeaderServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATHeaderService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATHeaderServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatheaderservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/header/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/header/__init__.py deleted file mode 100644 index 9bde850d82b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/header/__init__.py +++ /dev/null @@ -1,69 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_param_existing_key_request -from ._request_builders import build_response_existing_key_request -from ._request_builders import build_param_protected_key_request -from ._request_builders import build_response_protected_key_request -from ._request_builders import build_param_integer_request -from ._request_builders import build_response_integer_request -from ._request_builders import build_param_long_request -from ._request_builders import build_response_long_request -from ._request_builders import build_param_float_request -from ._request_builders import build_response_float_request -from ._request_builders import build_param_double_request -from ._request_builders import build_response_double_request -from ._request_builders import build_param_bool_request -from ._request_builders import build_response_bool_request -from ._request_builders import build_param_string_request -from ._request_builders import build_response_string_request -from ._request_builders import build_param_date_request -from ._request_builders import build_response_date_request -from ._request_builders import build_param_datetime_request -from ._request_builders import build_response_datetime_request -from ._request_builders import build_param_datetime_rfc1123_request -from ._request_builders import build_response_datetime_rfc1123_request -from ._request_builders import build_param_duration_request -from ._request_builders import build_response_duration_request -from ._request_builders import build_param_byte_request -from ._request_builders import build_response_byte_request -from ._request_builders import build_param_enum_request -from ._request_builders import build_response_enum_request -from ._request_builders import build_custom_request_id_request - -__all__ = [ - "build_param_existing_key_request", - "build_response_existing_key_request", - "build_param_protected_key_request", - "build_response_protected_key_request", - "build_param_integer_request", - "build_response_integer_request", - "build_param_long_request", - "build_response_long_request", - "build_param_float_request", - "build_response_float_request", - "build_param_double_request", - "build_response_double_request", - "build_param_bool_request", - "build_response_bool_request", - "build_param_string_request", - "build_response_string_request", - "build_param_date_request", - "build_response_date_request", - "build_param_datetime_request", - "build_response_datetime_request", - "build_param_datetime_rfc1123_request", - "build_response_datetime_rfc1123_request", - "build_param_duration_request", - "build_response_duration_request", - "build_param_byte_request", - "build_response_byte_request", - "build_param_enum_request", - "build_response_enum_request", - "build_custom_request_id_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/header/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/header/_request_builders.py deleted file mode 100644 index 4ec9fdee26c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/headerlowlevel/rest/header/_request_builders.py +++ /dev/null @@ -1,900 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_param_existing_key_request(*, user_agent_parameter: str, **kwargs: Any) -> HttpRequest: - """Send a post request with header value "User-Agent": "overwrite". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword user_agent_parameter: Send a post request with header value "User-Agent": "overwrite". - Required. - :paramtype user_agent_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/existingkey" - - # Construct headers - _headers["User-Agent"] = _SERIALIZER.header("user_agent_parameter", user_agent_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_existing_key_request(**kwargs: Any) -> HttpRequest: - """Get a response with header value "User-Agent": "overwrite". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/existingkey" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_protected_key_request(**kwargs: Any) -> HttpRequest: - """Send a post request with header value "Content-Type": "text/html". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Send a post request with header value "Content-Type": "text/html". - Required. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type") # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/protectedkey" - - # Construct headers - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_protected_key_request(**kwargs: Any) -> HttpRequest: - """Get a response with header value "Content-Type": "text/html". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/protectedkey" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_integer_request(*, scenario: str, value: int, **kwargs: Any) -> HttpRequest: - """Send a post request with header values "scenario": "positive", "value": 1 or "scenario": - "negative", "value": -2. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "positive" or "negative". - Required. - :paramtype scenario: str - :keyword value: Send a post request with header values 1 or -2. Required. - :paramtype value: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/integer" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["value"] = _SERIALIZER.header("value", value, "int") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_integer_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header value "value": 1 or -2. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "positive" or "negative". - Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/integer" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_long_request(*, scenario: str, value: int, **kwargs: Any) -> HttpRequest: - """Send a post request with header values "scenario": "positive", "value": 105 or "scenario": - "negative", "value": -2. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "positive" or "negative". - Required. - :paramtype scenario: str - :keyword value: Send a post request with header values 105 or -2. Required. - :paramtype value: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/long" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["value"] = _SERIALIZER.header("value", value, "int") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_long_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header value "value": 105 or -2. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "positive" or "negative". - Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/long" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_float_request(*, scenario: str, value: float, **kwargs: Any) -> HttpRequest: - """Send a post request with header values "scenario": "positive", "value": 0.07 or "scenario": - "negative", "value": -3.0. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "positive" or "negative". - Required. - :paramtype scenario: str - :keyword value: Send a post request with header values 0.07 or -3.0. Required. - :paramtype value: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/float" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["value"] = _SERIALIZER.header("value", value, "float") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_float_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header value "value": 0.07 or -3.0. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "positive" or "negative". - Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/float" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_double_request(*, scenario: str, value: float, **kwargs: Any) -> HttpRequest: - """Send a post request with header values "scenario": "positive", "value": 7e120 or "scenario": - "negative", "value": -3.0. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "positive" or "negative". - Required. - :paramtype scenario: str - :keyword value: Send a post request with header values 7e120 or -3.0. Required. - :paramtype value: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/double" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["value"] = _SERIALIZER.header("value", value, "float") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_double_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header value "value": 7e120 or -3.0. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "positive" or "negative". - Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/double" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_bool_request(*, scenario: str, value: bool, **kwargs: Any) -> HttpRequest: - """Send a post request with header values "scenario": "true", "value": true or "scenario": - "false", "value": false. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "true" or "false". - Required. - :paramtype scenario: str - :keyword value: Send a post request with header values true or false. Required. - :paramtype value: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/bool" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["value"] = _SERIALIZER.header("value", value, "bool") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_bool_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header value "value": true or false. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "true" or "false". - Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/bool" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_string_request(*, scenario: str, value: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Send a post request with header values "scenario": "valid", "value": "The quick brown fox jumps - over the lazy dog" or "scenario": "null", "value": null or "scenario": "empty", "value": "". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid" or "null" or - "empty". Required. - :paramtype scenario: str - :keyword value: Send a post request with header values "The quick brown fox jumps over the lazy - dog" or null or "". Default value is None. - :paramtype value: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/string" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - if value is not None: - _headers["value"] = _SERIALIZER.header("value", value, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_string_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header values "The quick brown fox jumps over the lazy dog" or null or "". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid" or "null" or - "empty". Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/string" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_date_request(*, scenario: str, value: datetime.date, **kwargs: Any) -> HttpRequest: - """Send a post request with header values "scenario": "valid", "value": "2010-01-01" or - "scenario": "min", "value": "0001-01-01". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid" or "min". - Required. - :paramtype scenario: str - :keyword value: Send a post request with header values "2010-01-01" or "0001-01-01". Required. - :paramtype value: ~datetime.date - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/date" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["value"] = _SERIALIZER.header("value", value, "date") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_date_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header values "2010-01-01" or "0001-01-01". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid" or "min". - Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/date" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_datetime_request(*, scenario: str, value: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Send a post request with header values "scenario": "valid", "value": "2010-01-01T12:34:56Z" or - "scenario": "min", "value": "0001-01-01T00:00:00Z". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid" or "min". - Required. - :paramtype scenario: str - :keyword value: Send a post request with header values "2010-01-01T12:34:56Z" or - "0001-01-01T00:00:00Z". Required. - :paramtype value: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/datetime" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["value"] = _SERIALIZER.header("value", value, "iso-8601") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_datetime_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header values "2010-01-01T12:34:56Z" or "0001-01-01T00:00:00Z". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid" or "min". - Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/datetime" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_datetime_rfc1123_request( - *, scenario: str, value: Optional[datetime.datetime] = None, **kwargs: Any -) -> HttpRequest: - """Send a post request with header values "scenario": "valid", "value": "Wed, 01 Jan 2010 12:34:56 - GMT" or "scenario": "min", "value": "Mon, 01 Jan 0001 00:00:00 GMT". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid" or "min". - Required. - :paramtype scenario: str - :keyword value: Send a post request with header values "Wed, 01 Jan 2010 12:34:56 GMT" or "Mon, - 01 Jan 0001 00:00:00 GMT". Default value is None. - :paramtype value: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/datetimerfc1123" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - if value is not None: - _headers["value"] = _SERIALIZER.header("value", value, "rfc-1123") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_datetime_rfc1123_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header values "Wed, 01 Jan 2010 12:34:56 GMT" or "Mon, 01 Jan 0001 00:00:00 - GMT". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid" or "min". - Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/datetimerfc1123" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_duration_request(*, scenario: str, value: datetime.timedelta, **kwargs: Any) -> HttpRequest: - """Send a post request with header values "scenario": "valid", "value": "P123DT22H14M12.011S". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid". Required. - :paramtype scenario: str - :keyword value: Send a post request with header values "P123DT22H14M12.011S". Required. - :paramtype value: ~datetime.timedelta - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/duration" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["value"] = _SERIALIZER.header("value", value, "duration") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_duration_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header values "P123DT22H14M12.011S". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid". Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/duration" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_byte_request(*, scenario: str, value: bytes, **kwargs: Any) -> HttpRequest: - """Send a post request with header values "scenario": "valid", "value": "啊齄丂狛狜隣郎隣兀﨩". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid". Required. - :paramtype scenario: str - :keyword value: Send a post request with header values "啊齄丂狛狜隣郎隣兀﨩". Required. - :paramtype value: bytes - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/byte" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["value"] = _SERIALIZER.header("value", value, "bytearray") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_byte_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header values "啊齄丂狛狜隣郎隣兀﨩". - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid". Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/byte" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_param_enum_request(*, scenario: str, value: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Send a post request with header values "scenario": "valid", "value": "GREY" or "scenario": - "null", "value": null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid" or "null" or - "empty". Required. - :paramtype scenario: str - :keyword value: Send a post request with header values 'GREY'. Known values are: "White", - "black", and "GREY". Default value is None. - :paramtype value: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/param/prim/enum" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - if value is not None: - _headers["value"] = _SERIALIZER.header("value", value, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_response_enum_request(*, scenario: str, **kwargs: Any) -> HttpRequest: - """Get a response with header values "GREY" or null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword scenario: Send a post request with header values "scenario": "valid" or "null" or - "empty". Required. - :paramtype scenario: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/response/prim/enum" - - # Construct headers - _headers["scenario"] = _SERIALIZER.header("scenario", scenario, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_custom_request_id_request(**kwargs: Any) -> HttpRequest: - """Send x-ms-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the - request. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/header/custom/x-ms-client-request-id/9C4D50EE-2D56-4CD3-8152-34347DC9F2B0" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/setup.py deleted file mode 100644 index 0ee80aaf09c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HeaderLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestswaggerbatheaderservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestSwaggerBATHeaderService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/__init__.py deleted file mode 100644 index 0e6c15464db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestHttpInfrastructureTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestHttpInfrastructureTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_client.py deleted file mode 100644 index 6646c3cd77f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestHttpInfrastructureTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestHttpInfrastructureTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestHttpInfrastructureTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `httpinfrastructurelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from httpinfrastructurelowlevel.rest import http_failure - >>> request = http_failure.build_get_empty_error_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestHttpInfrastructureTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_configuration.py deleted file mode 100644 index 71776ec85fd..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestHttpInfrastructureTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestHttpInfrastructureTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestHttpInfrastructureTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autoresthttpinfrastructuretestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/__init__.py deleted file mode 100644 index b1def3d097b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestHttpInfrastructureTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestHttpInfrastructureTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_client.py deleted file mode 100644 index 916773c14fa..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestHttpInfrastructureTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestHttpInfrastructureTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestHttpInfrastructureTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `httpinfrastructurelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from httpinfrastructurelowlevel.rest import http_failure - >>> request = http_failure.build_get_empty_error_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestHttpInfrastructureTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_configuration.py deleted file mode 100644 index cae367ee2b7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestHttpInfrastructureTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestHttpInfrastructureTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestHttpInfrastructureTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autoresthttpinfrastructuretestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_client_failure/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_client_failure/__init__.py deleted file mode 100644 index b33de025709..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_client_failure/__init__.py +++ /dev/null @@ -1,63 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_head400_request -from ._request_builders import build_get400_request -from ._request_builders import build_options400_request -from ._request_builders import build_put400_request -from ._request_builders import build_patch400_request -from ._request_builders import build_post400_request -from ._request_builders import build_delete400_request -from ._request_builders import build_head401_request -from ._request_builders import build_get402_request -from ._request_builders import build_options403_request -from ._request_builders import build_get403_request -from ._request_builders import build_put404_request -from ._request_builders import build_patch405_request -from ._request_builders import build_post406_request -from ._request_builders import build_delete407_request -from ._request_builders import build_put409_request -from ._request_builders import build_head410_request -from ._request_builders import build_get411_request -from ._request_builders import build_options412_request -from ._request_builders import build_get412_request -from ._request_builders import build_put413_request -from ._request_builders import build_patch414_request -from ._request_builders import build_post415_request -from ._request_builders import build_get416_request -from ._request_builders import build_delete417_request -from ._request_builders import build_head429_request - -__all__ = [ - "build_head400_request", - "build_get400_request", - "build_options400_request", - "build_put400_request", - "build_patch400_request", - "build_post400_request", - "build_delete400_request", - "build_head401_request", - "build_get402_request", - "build_options403_request", - "build_get403_request", - "build_put404_request", - "build_patch405_request", - "build_post406_request", - "build_delete407_request", - "build_put409_request", - "build_head410_request", - "build_get411_request", - "build_options412_request", - "build_get412_request", - "build_put413_request", - "build_patch414_request", - "build_post415_request", - "build_get416_request", - "build_delete417_request", - "build_head429_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_client_failure/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_client_failure/_request_builders.py deleted file mode 100644 index 75bbe41b139..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_client_failure/_request_builders.py +++ /dev/null @@ -1,744 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_head400_request(**kwargs: Any) -> HttpRequest: - """Return 400 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/400" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_get400_request(**kwargs: Any) -> HttpRequest: - """Return 400 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/400" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_options400_request(**kwargs: Any) -> HttpRequest: - """Return 400 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/400" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="OPTIONS", url=_url, headers=_headers, **kwargs) - - -def build_put400_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 400 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/400" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_patch400_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 400 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/400" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, json=json, **kwargs) - - -def build_post400_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 400 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/400" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_delete400_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 400 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/400" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, json=json, **kwargs) - - -def build_head401_request(**kwargs: Any) -> HttpRequest: - """Return 401 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/401" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_get402_request(**kwargs: Any) -> HttpRequest: - """Return 402 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/402" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_options403_request(**kwargs: Any) -> HttpRequest: - """Return 403 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/403" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="OPTIONS", url=_url, headers=_headers, **kwargs) - - -def build_get403_request(**kwargs: Any) -> HttpRequest: - """Return 403 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/403" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put404_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 404 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/404" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_patch405_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 405 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/405" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, json=json, **kwargs) - - -def build_post406_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 406 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/406" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_delete407_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 407 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/407" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, json=json, **kwargs) - - -def build_put409_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 409 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/409" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_head410_request(**kwargs: Any) -> HttpRequest: - """Return 410 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/410" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_get411_request(**kwargs: Any) -> HttpRequest: - """Return 411 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/411" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_options412_request(**kwargs: Any) -> HttpRequest: - """Return 412 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/412" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="OPTIONS", url=_url, headers=_headers, **kwargs) - - -def build_get412_request(**kwargs: Any) -> HttpRequest: - """Return 412 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/412" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put413_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 413 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/413" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_patch414_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 414 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/414" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, json=json, **kwargs) - - -def build_post415_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 415 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/415" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get416_request(**kwargs: Any) -> HttpRequest: - """Return 416 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/416" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_delete417_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 417 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/417" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, json=json, **kwargs) - - -def build_head429_request(**kwargs: Any) -> HttpRequest: - """Return 429 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/client/429" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_failure/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_failure/__init__.py deleted file mode 100644 index 6931dbc7cd9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_failure/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_empty_error_request -from ._request_builders import build_get_no_model_error_request -from ._request_builders import build_get_no_model_empty_request - -__all__ = [ - "build_get_empty_error_request", - "build_get_no_model_error_request", - "build_get_no_model_empty_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_failure/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_failure/_request_builders.py deleted file mode 100644 index ea09c04e2a6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_failure/_request_builders.py +++ /dev/null @@ -1,91 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_empty_error_request(**kwargs: Any) -> HttpRequest: - """Get empty error form server. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/emptybody/error" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_no_model_error_request(**kwargs: Any) -> HttpRequest: - """Get empty error form server. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/nomodel/error" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_no_model_empty_request(**kwargs: Any) -> HttpRequest: - """Get empty response from server. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/nomodel/empty" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_redirects/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_redirects/__init__.py deleted file mode 100644 index bd5acc91340..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_redirects/__init__.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_head300_request -from ._request_builders import build_get300_request -from ._request_builders import build_head301_request -from ._request_builders import build_get301_request -from ._request_builders import build_put301_request -from ._request_builders import build_head302_request -from ._request_builders import build_get302_request -from ._request_builders import build_patch302_request -from ._request_builders import build_post303_request -from ._request_builders import build_head307_request -from ._request_builders import build_get307_request -from ._request_builders import build_options307_request -from ._request_builders import build_put307_request -from ._request_builders import build_patch307_request -from ._request_builders import build_post307_request -from ._request_builders import build_delete307_request - -__all__ = [ - "build_head300_request", - "build_get300_request", - "build_head301_request", - "build_get301_request", - "build_put301_request", - "build_head302_request", - "build_get302_request", - "build_patch302_request", - "build_post303_request", - "build_head307_request", - "build_get307_request", - "build_options307_request", - "build_put307_request", - "build_patch307_request", - "build_post307_request", - "build_delete307_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_redirects/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_redirects/_request_builders.py deleted file mode 100644 index 92a6876f20b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_redirects/_request_builders.py +++ /dev/null @@ -1,461 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_head300_request(**kwargs: Any) -> HttpRequest: - """Return 300 status code and redirect to /http/success/200. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/300" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_get300_request(**kwargs: Any) -> HttpRequest: - """Return 300 status code and redirect to /http/success/200. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/300" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_head301_request(**kwargs: Any) -> HttpRequest: - """Return 301 status code and redirect to /http/success/200. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/301" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_get301_request(**kwargs: Any) -> HttpRequest: - """Return 301 status code and redirect to /http/success/200. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/301" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put301_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Put true Boolean value in request returns 301. This request should not be automatically - redirected, but should return the received 301 to the caller for evaluation. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/301" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_head302_request(**kwargs: Any) -> HttpRequest: - """Return 302 status code and redirect to /http/success/200. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/302" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_get302_request(**kwargs: Any) -> HttpRequest: - """Return 302 status code and redirect to /http/success/200. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/302" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_patch302_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Patch true Boolean value in request returns 302. This request should not be automatically - redirected, but should return the received 302 to the caller for evaluation. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/302" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, json=json, **kwargs) - - -def build_post303_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Post true Boolean value in request returns 303. This request should be automatically - redirected usign a get, ultimately returning a 200 status code. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/303" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_head307_request(**kwargs: Any) -> HttpRequest: - """Redirect with 307, resulting in a 200 success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/307" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_get307_request(**kwargs: Any) -> HttpRequest: - """Redirect get with 307, resulting in a 200 success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/307" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_options307_request(**kwargs: Any) -> HttpRequest: - """options redirected with 307, resulting in a 200 after redirect. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/307" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="OPTIONS", url=_url, headers=_headers, **kwargs) - - -def build_put307_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Put redirected with 307, resulting in a 200 after redirect. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/307" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_patch307_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Patch redirected with 307, resulting in a 200 after redirect. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/307" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, json=json, **kwargs) - - -def build_post307_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Post redirected with 307, resulting in a 200 after redirect. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/307" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_delete307_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Delete redirected with 307, resulting in a 200 after redirect. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/redirect/307" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, json=json, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_retry/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_retry/__init__.py deleted file mode 100644 index 9ead470ba37..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_retry/__init__.py +++ /dev/null @@ -1,29 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_head408_request -from ._request_builders import build_put500_request -from ._request_builders import build_patch500_request -from ._request_builders import build_get502_request -from ._request_builders import build_options502_request -from ._request_builders import build_post503_request -from ._request_builders import build_delete503_request -from ._request_builders import build_put504_request -from ._request_builders import build_patch504_request - -__all__ = [ - "build_head408_request", - "build_put500_request", - "build_patch500_request", - "build_get502_request", - "build_options502_request", - "build_post503_request", - "build_delete503_request", - "build_put504_request", - "build_patch504_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_retry/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_retry/_request_builders.py deleted file mode 100644 index 4ece9c8d812..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_retry/_request_builders.py +++ /dev/null @@ -1,277 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_head408_request(**kwargs: Any) -> HttpRequest: - """Return 408 status code, then 200 after retry. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/retry/408" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_put500_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 500 status code, then 200 after retry. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/retry/500" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_patch500_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 500 status code, then 200 after retry. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/retry/500" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get502_request(**kwargs: Any) -> HttpRequest: - """Return 502 status code, then 200 after retry. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/retry/502" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_options502_request(**kwargs: Any) -> HttpRequest: - """Return 502 status code, then 200 after retry. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/retry/502" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="OPTIONS", url=_url, headers=_headers, **kwargs) - - -def build_post503_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 503 status code, then 200 after retry. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/retry/503" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_delete503_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 503 status code, then 200 after retry. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/retry/503" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, json=json, **kwargs) - - -def build_put504_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 504 status code, then 200 after retry. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/retry/504" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_patch504_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 504 status code, then 200 after retry. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/retry/504" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, json=json, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_server_failure/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_server_failure/__init__.py deleted file mode 100644 index 192eb9ee4f4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_server_failure/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_head501_request -from ._request_builders import build_get501_request -from ._request_builders import build_post505_request -from ._request_builders import build_delete505_request - -__all__ = [ - "build_head501_request", - "build_get501_request", - "build_post505_request", - "build_delete505_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_server_failure/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_server_failure/_request_builders.py deleted file mode 100644 index 57a1dfd3df3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_server_failure/_request_builders.py +++ /dev/null @@ -1,128 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_head501_request(**kwargs: Any) -> HttpRequest: - """Return 501 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/server/501" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_get501_request(**kwargs: Any) -> HttpRequest: - """Return 501 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/server/501" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_post505_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 505 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/server/505" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_delete505_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Return 505 status code - should be represented in the client as an error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/failure/server/505" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, json=json, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_success/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_success/__init__.py deleted file mode 100644 index 229a3222f9a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_success/__init__.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_head200_request -from ._request_builders import build_get200_request -from ._request_builders import build_options200_request -from ._request_builders import build_put200_request -from ._request_builders import build_patch200_request -from ._request_builders import build_post200_request -from ._request_builders import build_delete200_request -from ._request_builders import build_put201_request -from ._request_builders import build_post201_request -from ._request_builders import build_put202_request -from ._request_builders import build_patch202_request -from ._request_builders import build_post202_request -from ._request_builders import build_delete202_request -from ._request_builders import build_head204_request -from ._request_builders import build_put204_request -from ._request_builders import build_patch204_request -from ._request_builders import build_post204_request -from ._request_builders import build_delete204_request -from ._request_builders import build_head404_request - -__all__ = [ - "build_head200_request", - "build_get200_request", - "build_options200_request", - "build_put200_request", - "build_patch200_request", - "build_post200_request", - "build_delete200_request", - "build_put201_request", - "build_post201_request", - "build_put202_request", - "build_patch202_request", - "build_post202_request", - "build_delete202_request", - "build_head204_request", - "build_put204_request", - "build_patch204_request", - "build_post204_request", - "build_delete204_request", - "build_head404_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_success/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_success/_request_builders.py deleted file mode 100644 index 82829ca3953..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/http_success/_request_builders.py +++ /dev/null @@ -1,575 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_head200_request(**kwargs: Any) -> HttpRequest: - """Return 200 status code if successful. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/200" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_get200_request(**kwargs: Any) -> HttpRequest: - """Get 200 success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/200" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_options200_request(**kwargs: Any) -> HttpRequest: - """Options 200 success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/200" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="OPTIONS", url=_url, headers=_headers, **kwargs) - - -def build_put200_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Put boolean value true returning 200 success. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_patch200_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Patch true Boolean value in request returning 200. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, json=json, **kwargs) - - -def build_post200_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Post bollean value true in request that returns a 200. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_delete200_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Delete simple boolean value true returns 200. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/200" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, json=json, **kwargs) - - -def build_put201_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Put true Boolean value in request returns 201. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/201" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_post201_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Post true Boolean value in request returns 201 (Created). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/201" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_put202_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Put true Boolean value in request returns 202 (Accepted). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/202" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_patch202_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Patch true Boolean value in request returns 202. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/202" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, json=json, **kwargs) - - -def build_post202_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Post true Boolean value in request returns 202 (Accepted). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/202" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_delete202_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Delete true Boolean value in request returns 202 (accepted). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/202" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, json=json, **kwargs) - - -def build_head204_request(**kwargs: Any) -> HttpRequest: - """Return 204 status code if successful. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/204" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) - - -def build_put204_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Put true Boolean value in request returns 204 (no content). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/204" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_patch204_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Patch true Boolean value in request returns 204 (no content). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/204" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, json=json, **kwargs) - - -def build_post204_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Post true Boolean value in request returns 204 (no content). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/204" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_delete204_request(*, json: bool = True, **kwargs: Any) -> HttpRequest: - """Delete true Boolean value in request returns 204 (no content). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Simple boolean value true. Known values are True and None. Default value is - True. - :paramtype json: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/204" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="DELETE", url=_url, headers=_headers, json=json, **kwargs) - - -def build_head404_request(**kwargs: Any) -> HttpRequest: - """Return 404 status code. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/success/404" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="HEAD", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/multiple_responses/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/multiple_responses/__init__.py deleted file mode 100644 index 83f478827e0..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/multiple_responses/__init__.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get200_model204_no_model_default_error200_valid_request -from ._request_builders import build_get200_model204_no_model_default_error204_valid_request -from ._request_builders import build_get200_model204_no_model_default_error201_invalid_request -from ._request_builders import build_get200_model204_no_model_default_error202_none_request -from ._request_builders import build_get200_model204_no_model_default_error400_valid_request -from ._request_builders import build_get200_model201_model_default_error200_valid_request -from ._request_builders import build_get200_model201_model_default_error201_valid_request -from ._request_builders import build_get200_model201_model_default_error400_valid_request -from ._request_builders import build_get200_model_a201_model_c404_model_d_default_error200_valid_request -from ._request_builders import build_get200_model_a201_model_c404_model_d_default_error201_valid_request -from ._request_builders import build_get200_model_a201_model_c404_model_d_default_error404_valid_request -from ._request_builders import build_get200_model_a201_model_c404_model_d_default_error400_valid_request -from ._request_builders import build_get202_none204_none_default_error202_none_request -from ._request_builders import build_get202_none204_none_default_error204_none_request -from ._request_builders import build_get202_none204_none_default_error400_valid_request -from ._request_builders import build_get202_none204_none_default_none202_invalid_request -from ._request_builders import build_get202_none204_none_default_none204_none_request -from ._request_builders import build_get202_none204_none_default_none400_none_request -from ._request_builders import build_get202_none204_none_default_none400_invalid_request -from ._request_builders import build_get_default_model_a200_valid_request -from ._request_builders import build_get_default_model_a200_none_request -from ._request_builders import build_get_default_model_a400_valid_request -from ._request_builders import build_get_default_model_a400_none_request -from ._request_builders import build_get_default_none200_invalid_request -from ._request_builders import build_get_default_none200_none_request -from ._request_builders import build_get_default_none400_invalid_request -from ._request_builders import build_get_default_none400_none_request -from ._request_builders import build_get200_model_a200_none_request -from ._request_builders import build_get200_model_a200_valid_request -from ._request_builders import build_get200_model_a200_invalid_request -from ._request_builders import build_get200_model_a400_none_request -from ._request_builders import build_get200_model_a400_valid_request -from ._request_builders import build_get200_model_a400_invalid_request -from ._request_builders import build_get200_model_a202_valid_request - -__all__ = [ - "build_get200_model204_no_model_default_error200_valid_request", - "build_get200_model204_no_model_default_error204_valid_request", - "build_get200_model204_no_model_default_error201_invalid_request", - "build_get200_model204_no_model_default_error202_none_request", - "build_get200_model204_no_model_default_error400_valid_request", - "build_get200_model201_model_default_error200_valid_request", - "build_get200_model201_model_default_error201_valid_request", - "build_get200_model201_model_default_error400_valid_request", - "build_get200_model_a201_model_c404_model_d_default_error200_valid_request", - "build_get200_model_a201_model_c404_model_d_default_error201_valid_request", - "build_get200_model_a201_model_c404_model_d_default_error404_valid_request", - "build_get200_model_a201_model_c404_model_d_default_error400_valid_request", - "build_get202_none204_none_default_error202_none_request", - "build_get202_none204_none_default_error204_none_request", - "build_get202_none204_none_default_error400_valid_request", - "build_get202_none204_none_default_none202_invalid_request", - "build_get202_none204_none_default_none204_none_request", - "build_get202_none204_none_default_none400_none_request", - "build_get202_none204_none_default_none400_invalid_request", - "build_get_default_model_a200_valid_request", - "build_get_default_model_a200_none_request", - "build_get_default_model_a400_valid_request", - "build_get_default_model_a400_none_request", - "build_get_default_none200_invalid_request", - "build_get_default_none200_none_request", - "build_get_default_none400_invalid_request", - "build_get_default_none400_none_request", - "build_get200_model_a200_none_request", - "build_get200_model_a200_valid_request", - "build_get200_model_a200_invalid_request", - "build_get200_model_a400_none_request", - "build_get200_model_a400_valid_request", - "build_get200_model_a400_invalid_request", - "build_get200_model_a202_valid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/multiple_responses/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/multiple_responses/_request_builders.py deleted file mode 100644 index 3a85f191dd5..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/httpinfrastructurelowlevel/rest/multiple_responses/_request_builders.py +++ /dev/null @@ -1,811 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get200_model204_no_model_default_error200_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with valid payload: {'statusCode': '200'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/204/none/default/Error/response/200/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model204_no_model_default_error204_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 204 response with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/204/none/default/Error/response/204/none" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model204_no_model_default_error201_invalid_request(**kwargs: Any) -> HttpRequest: - """Send a 201 response with valid payload: {'statusCode': '201'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/204/none/default/Error/response/201/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model204_no_model_default_error202_none_request(**kwargs: Any) -> HttpRequest: - """Send a 202 response with no payload:. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/204/none/default/Error/response/202/none" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model204_no_model_default_error400_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 400 response with valid error payload: {'status': 400, 'message': 'client error'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/204/none/default/Error/response/400/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model201_model_default_error200_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with valid payload: {'statusCode': '200'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/201/B/default/Error/response/200/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model201_model_default_error201_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 201 response with valid payload: {'statusCode': '201', 'textStatusCode': 'Created'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/201/B/default/Error/response/201/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model201_model_default_error400_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 400 response with valid payload: {'code': '400', 'message': 'client error'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/201/B/default/Error/response/400/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model_a201_model_c404_model_d_default_error200_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with valid payload: {'statusCode': '200'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/201/C/404/D/default/Error/response/200/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model_a201_model_c404_model_d_default_error201_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with valid payload: {'httpCode': '201'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/201/C/404/D/default/Error/response/201/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model_a201_model_c404_model_d_default_error404_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with valid payload: {'httpStatusCode': '404'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/201/C/404/D/default/Error/response/404/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model_a201_model_c404_model_d_default_error400_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 400 response with valid payload: {'code': '400', 'message': 'client error'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/201/C/404/D/default/Error/response/400/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get202_none204_none_default_error202_none_request(**kwargs: Any) -> HttpRequest: - """Send a 202 response with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/202/none/204/none/default/Error/response/202/none" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get202_none204_none_default_error204_none_request(**kwargs: Any) -> HttpRequest: - """Send a 204 response with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/202/none/204/none/default/Error/response/204/none" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get202_none204_none_default_error400_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 400 response with valid payload: {'code': '400', 'message': 'client error'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/202/none/204/none/default/Error/response/400/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get202_none204_none_default_none202_invalid_request(**kwargs: Any) -> HttpRequest: - """Send a 202 response with an unexpected payload {'property': 'value'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/payloads/202/none/204/none/default/none/response/202/invalid" - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_get202_none204_none_default_none204_none_request(**kwargs: Any) -> HttpRequest: - """Send a 204 response with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/payloads/202/none/204/none/default/none/response/204/none" - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_get202_none204_none_default_none400_none_request(**kwargs: Any) -> HttpRequest: - """Send a 400 response with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/payloads/202/none/204/none/default/none/response/400/none" - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_get202_none204_none_default_none400_invalid_request(**kwargs: Any) -> HttpRequest: - """Send a 400 response with an unexpected payload {'property': 'value'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/payloads/202/none/204/none/default/none/response/400/invalid" - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_get_default_model_a200_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with valid payload: {'statusCode': '200'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/default/A/response/200/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_default_model_a200_none_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/default/A/response/200/none" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_default_model_a400_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 400 response with valid payload: {'statusCode': '400'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/default/A/response/400/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_default_model_a400_none_request(**kwargs: Any) -> HttpRequest: - """Send a 400 response with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/default/A/response/400/none" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_default_none200_invalid_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with invalid payload: {'statusCode': '200'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/payloads/default/none/response/200/invalid" - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_get_default_none200_none_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/payloads/default/none/response/200/none" - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_get_default_none400_invalid_request(**kwargs: Any) -> HttpRequest: - """Send a 400 response with valid payload: {'statusCode': '400'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/payloads/default/none/response/400/invalid" - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_get_default_none400_none_request(**kwargs: Any) -> HttpRequest: - """Send a 400 response with no payload. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/http/payloads/default/none/response/400/none" - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_get200_model_a200_none_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with no payload, when a payload is expected - client should return a null - object of thde type for model A. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/response/200/none" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model_a200_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with payload {'statusCode': '200'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/response/200/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model_a200_invalid_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with invalid payload {'statusCodeInvalid': '200'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/response/200/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model_a400_none_request(**kwargs: Any) -> HttpRequest: - """Send a 400 response with no payload client should treat as an http error with no error model. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/response/400/none" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model_a400_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with payload {'statusCode': '400'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/response/400/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model_a400_invalid_request(**kwargs: Any) -> HttpRequest: - """Send a 200 response with invalid payload {'statusCodeInvalid': '400'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/response/400/invalid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get200_model_a202_valid_request(**kwargs: Any) -> HttpRequest: - """Send a 202 response with payload {'statusCode': '202'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/http/payloads/200/A/response/202/valid" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/setup.py deleted file mode 100644 index 3e59c81effc..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/HttpLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autoresthttpinfrastructuretestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestHttpInfrastructureTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/__init__.py deleted file mode 100644 index b8941984406..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import IncorrectReturnedErrorModel -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["IncorrectReturnedErrorModel"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_client.py deleted file mode 100644 index 79b68f232c7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_client.py +++ /dev/null @@ -1,75 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import IncorrectReturnedErrorModelConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class IncorrectReturnedErrorModel: # pylint: disable=client-accepts-api-version-keyword - """Test to see when throwing an HttpResponseError whether we swallow error model deserialization - errors. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = IncorrectReturnedErrorModelConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `incorrecterrorresponselowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from incorrecterrorresponselowlevel.rest import build_get_incorrect_error_from_server_request - >>> request = build_get_incorrect_error_from_server_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> IncorrectReturnedErrorModel - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_configuration.py deleted file mode 100644 index 848911b2ef4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class IncorrectReturnedErrorModelConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for IncorrectReturnedErrorModel. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(IncorrectReturnedErrorModelConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "incorrectreturnederrormodel/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/__init__.py deleted file mode 100644 index 51e412bfc61..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import IncorrectReturnedErrorModel - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["IncorrectReturnedErrorModel"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_client.py deleted file mode 100644 index a8b988bd065..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_client.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import IncorrectReturnedErrorModelConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class IncorrectReturnedErrorModel: # pylint: disable=client-accepts-api-version-keyword - """Test to see when throwing an HttpResponseError whether we swallow error model deserialization - errors. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = IncorrectReturnedErrorModelConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `incorrecterrorresponselowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from incorrecterrorresponselowlevel.rest import build_get_incorrect_error_from_server_request - >>> request = build_get_incorrect_error_from_server_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "IncorrectReturnedErrorModel": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_configuration.py deleted file mode 100644 index 1b670d174d9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class IncorrectReturnedErrorModelConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for IncorrectReturnedErrorModel. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(IncorrectReturnedErrorModelConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "incorrectreturnederrormodel/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/rest/__init__.py deleted file mode 100644 index 3acb65b5a9c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/rest/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_incorrect_error_from_server_request - -__all__ = [ - "build_get_incorrect_error_from_server_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/rest/_request_builders.py deleted file mode 100644 index 544576d101e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/incorrecterrorresponselowlevel/rest/_request_builders.py +++ /dev/null @@ -1,34 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest - -from .._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_incorrect_error_from_server_request(**kwargs: Any) -> HttpRequest: - """Get an error response from the server that is not as described in our Error object. Want to - swallow the deserialization error and still return an HttpResponseError to the users. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/incorrectError" - - return HttpRequest(method="GET", url=_url, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/setup.py deleted file mode 100644 index b139260faaa..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/IncorrectErrorResponseLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "incorrectreturnederrormodel" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="IncorrectReturnedErrorModel", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test to see when throwing an HttpResponseError whether we swallow error model deserialization errors. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/__init__.py deleted file mode 100644 index 87cd569b0c4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import MediaTypesClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["MediaTypesClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_client.py deleted file mode 100644 index ea74b1045f9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import MediaTypesClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class MediaTypesClient: # pylint: disable=client-accepts-api-version-keyword - """Play with produces/consumes and media-types in general. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = MediaTypesClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `mediatypeslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from mediatypeslowlevel.rest import build_analyze_body_request - >>> request = build_analyze_body_request(content_type=content_type, json=json, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> MediaTypesClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_configuration.py deleted file mode 100644 index 3628a4a853e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class MediaTypesClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for MediaTypesClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(MediaTypesClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "mediatypesclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/__init__.py deleted file mode 100644 index 8e67164029c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import MediaTypesClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["MediaTypesClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_client.py deleted file mode 100644 index 17717ad88d6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import MediaTypesClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class MediaTypesClient: # pylint: disable=client-accepts-api-version-keyword - """Play with produces/consumes and media-types in general. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = MediaTypesClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `mediatypeslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from mediatypeslowlevel.rest import build_analyze_body_request - >>> request = build_analyze_body_request(content_type=content_type, json=json, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "MediaTypesClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_configuration.py deleted file mode 100644 index ac6169f2c7c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class MediaTypesClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for MediaTypesClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(MediaTypesClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "mediatypesclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/rest/__init__.py deleted file mode 100644 index b29f866c15e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/rest/__init__.py +++ /dev/null @@ -1,25 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_analyze_body_request -from ._request_builders import build_analyze_body_no_accept_header_request -from ._request_builders import build_content_type_with_encoding_request -from ._request_builders import build_binary_body_with_two_content_types_request -from ._request_builders import build_binary_body_with_three_content_types_request -from ._request_builders import build_body_three_types_request -from ._request_builders import build_put_text_and_json_body_request - -__all__ = [ - "build_analyze_body_request", - "build_analyze_body_no_accept_header_request", - "build_content_type_with_encoding_request", - "build_binary_body_with_two_content_types_request", - "build_binary_body_with_three_content_types_request", - "build_body_three_types_request", - "build_put_text_and_json_body_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/rest/_request_builders.py deleted file mode 100644 index 5081f8902a4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/mediatypeslowlevel/rest/_request_builders.py +++ /dev/null @@ -1,411 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -@overload -def build_analyze_body_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Analyze body, that could be different media types. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Input parameter. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "source": "str" # Optional. File source path. - } - """ - - -@overload -def build_analyze_body_request(*, content_type: str, content: Optional[IO] = None, **kwargs: Any) -> HttpRequest: - """Analyze body, that could be different media types. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'application/pdf', 'image/jpeg', 'image/png', - 'image/tiff'. Required. - :paramtype content_type: str - :keyword content: Input parameter. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_analyze_body_request(**kwargs: Any) -> HttpRequest: - """Analyze body, that could be different media types. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json', - 'application/pdf', 'image/jpeg', 'image/png', 'image/tiff'. Default value is None. - :paramtype content_type: str - :keyword json: Input parameter. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/mediatypes/analyze" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_analyze_body_no_accept_header_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Analyze body, that could be different media types. Adds to AnalyzeBody by not having an accept - type. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Input parameter. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "source": "str" # Optional. File source path. - } - """ - - -@overload -def build_analyze_body_no_accept_header_request( - *, content_type: str, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Analyze body, that could be different media types. Adds to AnalyzeBody by not having an accept - type. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'application/pdf', 'image/jpeg', 'image/png', - 'image/tiff'. Required. - :paramtype content_type: str - :keyword content: Input parameter. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_analyze_body_no_accept_header_request(**kwargs: Any) -> HttpRequest: - """Analyze body, that could be different media types. Adds to AnalyzeBody by not having an accept - type. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json', - 'application/pdf', 'image/jpeg', 'image/png', 'image/tiff'. Default value is None. - :paramtype content_type: str - :keyword json: Input parameter. Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/mediatypes/analyzeNoAccept" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_content_type_with_encoding_request(*, content: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Pass in contentType 'text/plain; charset=UTF-8' to pass test. Value for input does not matter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Input parameter. Default value is None. - :paramtype content: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/mediatypes/contentTypeWithEncoding" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, content=content, **kwargs) - - -def build_binary_body_with_two_content_types_request(*, content: IO, **kwargs: Any) -> HttpRequest: - """Binary body with two content types. Pass in of {'hello': 'world'} for the application/json - content type, and a byte stream of 'hello, world!' for application/octet-stream. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: The payload body. Required. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "text/plain") - - # Construct URL - _url = "/mediatypes/binaryBodyTwoContentTypes" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, content=content, **kwargs) - - -def build_binary_body_with_three_content_types_request(*, content: IO, **kwargs: Any) -> HttpRequest: - """Binary body with three content types. Pass in string 'hello, world' with content type - 'text/plain', {'hello': world'} with content type 'application/json' and a byte string for - 'application/octet-stream'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: The payload body. Required. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "text/plain") - - # Construct URL - _url = "/mediatypes/binaryBodyThreeContentTypes" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, content=content, **kwargs) - - -@overload -def build_body_three_types_request(*, json: Any, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Body with three types. Can be stream, string, or JSON. Pass in string 'hello, world' with - content type 'text/plain', {'hello': world'} with content type 'application/json' and a byte - string for 'application/octet-stream'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: The payload body. Required. - :paramtype json: any - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -@overload -def build_body_three_types_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Body with three types. Can be stream, string, or JSON. Pass in string 'hello, world' with - content type 'text/plain', {'hello': world'} with content type 'application/json' and a byte - string for 'application/octet-stream'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: The payload body. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Known values are: 'application/json', 'application/octet-stream', 'text/plain'. Default value - is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -@overload -def build_body_three_types_request(*, content: str, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Body with three types. Can be stream, string, or JSON. Pass in string 'hello, world' with - content type 'text/plain', {'hello': world'} with content type 'application/json' and a byte - string for 'application/octet-stream'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: The payload body. Required. - :paramtype content: str - :keyword content_type: Body Parameter content-type. Content type parameter for string body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_body_three_types_request(**kwargs: Any) -> HttpRequest: - """Body with three types. Can be stream, string, or JSON. Pass in string 'hello, world' with - content type 'text/plain', {'hello': world'} with content type 'application/json' and a byte - string for 'application/octet-stream'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: The payload body. Is one of the following types: any, IO, string Required. - :paramtype json: any or IO or str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json', - 'application/octet-stream', 'text/plain'. Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "text/plain") - - # Construct URL - _url = "/mediatypes/bodyThreeTypes" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_put_text_and_json_body_request(*, content: str, **kwargs: Any) -> HttpRequest: - """Body that's either text/plain or application/json. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: The payload body. Required. - :paramtype content: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "text/plain") - - # Construct URL - _url = "/mediatypes/textAndJson" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, content=content, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/setup.py deleted file mode 100644 index 89e2bf332f7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MediaTypesLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "mediatypesclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="MediaTypesClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Play with produces/consumes and media-types in general. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/__init__.py deleted file mode 100644 index cdb2a00692b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import MergePatchJsonClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["MergePatchJsonClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_client.py deleted file mode 100644 index 7d9dbffb112..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import MergePatchJsonClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class MergePatchJsonClient: # pylint: disable=client-accepts-api-version-keyword - """Service client for testing merge patch json. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = MergePatchJsonClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `mergepatchjsonlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from mergepatchjsonlowlevel.rest import build_patch_single_request - >>> request = build_patch_single_request(json=json, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> MergePatchJsonClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_configuration.py deleted file mode 100644 index 561421f9619..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class MergePatchJsonClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for MergePatchJsonClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(MergePatchJsonClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "mergepatchjsonclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/__init__.py deleted file mode 100644 index a0183158aa9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import MergePatchJsonClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["MergePatchJsonClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_client.py deleted file mode 100644 index da0adee240e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import MergePatchJsonClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class MergePatchJsonClient: # pylint: disable=client-accepts-api-version-keyword - """Service client for testing merge patch json. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = MergePatchJsonClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `mergepatchjsonlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from mergepatchjsonlowlevel.rest import build_patch_single_request - >>> request = build_patch_single_request(json=json, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "MergePatchJsonClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_configuration.py deleted file mode 100644 index 2b49cb02c75..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class MergePatchJsonClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for MergePatchJsonClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(MergePatchJsonClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "mergepatchjsonclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/rest/__init__.py deleted file mode 100644 index 55d58fa832d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/rest/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_patch_single_request - -__all__ = [ - "build_patch_single_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/rest/_request_builders.py deleted file mode 100644 index d1a88b6b4b0..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/mergepatchjsonlowlevel/rest/_request_builders.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_patch_single_request(*, json: JSON, **kwargs: Any) -> HttpRequest: - """Basic patch with an object. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Pass in {'foo': 'bar'} for a 200, anything else for an object error. Required. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/mergePatchJson/single" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, json=json, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/setup.py deleted file mode 100644 index b39358823a7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MergePatchJsonLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "mergepatchjsonclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="MergePatchJsonClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Service client for testing merge patch json. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/__init__.py deleted file mode 100644 index 2a9a92d1f03..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestResourceFlatteningTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestResourceFlatteningTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_client.py deleted file mode 100644 index f8ad89a94d4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestResourceFlatteningTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestResourceFlatteningTestService: # pylint: disable=client-accepts-api-version-keyword - """Resource Flattening for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestResourceFlatteningTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `modelflatteninglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from modelflatteninglowlevel.rest import build_put_array_request - >>> request = build_put_array_request(content_type=content_type, json=json, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestResourceFlatteningTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_configuration.py deleted file mode 100644 index 7244a93c346..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestResourceFlatteningTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestResourceFlatteningTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestResourceFlatteningTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestresourceflatteningtestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_vendor.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/__init__.py deleted file mode 100644 index ba69a9621ff..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestResourceFlatteningTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestResourceFlatteningTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_client.py deleted file mode 100644 index 20ee26546eb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestResourceFlatteningTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestResourceFlatteningTestService: # pylint: disable=client-accepts-api-version-keyword - """Resource Flattening for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestResourceFlatteningTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `modelflatteninglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from modelflatteninglowlevel.rest import build_put_array_request - >>> request = build_put_array_request(content_type=content_type, json=json, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestResourceFlatteningTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_configuration.py deleted file mode 100644 index 73c510afe25..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestResourceFlatteningTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestResourceFlatteningTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestResourceFlatteningTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestresourceflatteningtestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/rest/__init__.py deleted file mode 100644 index 47ca70c60b9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/rest/__init__.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_put_array_request -from ._request_builders import build_get_array_request -from ._request_builders import build_put_wrapped_array_request -from ._request_builders import build_get_wrapped_array_request -from ._request_builders import build_put_dictionary_request -from ._request_builders import build_get_dictionary_request -from ._request_builders import build_put_resource_collection_request -from ._request_builders import build_get_resource_collection_request -from ._request_builders import build_put_simple_product_request -from ._request_builders import build_post_flattened_simple_product_request -from ._request_builders import build_put_simple_product_with_grouping_request - -__all__ = [ - "build_put_array_request", - "build_get_array_request", - "build_put_wrapped_array_request", - "build_get_wrapped_array_request", - "build_put_dictionary_request", - "build_get_dictionary_request", - "build_put_resource_collection_request", - "build_get_resource_collection_request", - "build_put_simple_product_request", - "build_post_flattened_simple_product_request", - "build_put_simple_product_with_grouping_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/rest/_request_builders.py deleted file mode 100644 index 18859b0eb6c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/modelflatteninglowlevel/rest/_request_builders.py +++ /dev/null @@ -1,853 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Dict, IO, List, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer -from .._vendor import _format_url_section - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -@overload -def build_put_array_request( - *, content_type: Optional[str] = None, json: Optional[List[JSON]] = None, **kwargs: Any -) -> HttpRequest: - """Put External Resource as an Array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: External Resource as an Array to put. Default value is None. - :paramtype json: list[JSON] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - ] - """ - - -@overload -def build_put_array_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Put External Resource as an Array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: External Resource as an Array to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_array_request(**kwargs: Any) -> HttpRequest: - """Put External Resource as an Array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: External Resource as an Array to put. Is either a list type or a IO type. - Default value is None. - :paramtype json: list[JSON] or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/model-flatten/array" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_array_request(**kwargs: Any) -> HttpRequest: - """Get External Resource as an Array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/model-flatten/array" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_wrapped_array_request( - *, content_type: Optional[str] = None, json: Optional[List[JSON]] = None, **kwargs: Any -) -> HttpRequest: - """No need to have a route in Express server for this operation. Used to verify the type flattened - is not removed if it's referenced in an array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: External Resource as an Array to put. Default value is None. - :paramtype json: list[JSON] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - { - "value": "str" # Optional. the product value. - } - ] - """ - - -@overload -def build_put_wrapped_array_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """No need to have a route in Express server for this operation. Used to verify the type flattened - is not removed if it's referenced in an array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: External Resource as an Array to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_wrapped_array_request(**kwargs: Any) -> HttpRequest: - """No need to have a route in Express server for this operation. Used to verify the type flattened - is not removed if it's referenced in an array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: External Resource as an Array to put. Is either a list type or a IO type. - Default value is None. - :paramtype json: list[JSON] or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/model-flatten/wrappedarray" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_wrapped_array_request(**kwargs: Any) -> HttpRequest: - """No need to have a route in Express server for this operation. Used to verify the type flattened - is not removed if it's referenced in an array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/model-flatten/wrappedarray" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_dictionary_request( - *, content_type: Optional[str] = None, json: Optional[Dict[str, JSON]] = None, **kwargs: Any -) -> HttpRequest: - """Put External Resource as a Dictionary. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: External Resource as a Dictionary to put. Default value is None. - :paramtype json: dict[str, JSON] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "str": { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "p.name": "str", # Optional. - "provisioningState": "str", # Optional. - "provisioningStateValues": "str", # Optional. Known values - are: "Succeeded", "Failed", "canceled", "Accepted", "Creating", - "Created", "Updating", "Updated", "Deleting", "Deleted", and "OK". - "type": "str" # Optional. - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - } - """ - - -@overload -def build_put_dictionary_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Put External Resource as a Dictionary. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: External Resource as a Dictionary to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_dictionary_request(**kwargs: Any) -> HttpRequest: - """Put External Resource as a Dictionary. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: External Resource as a Dictionary to put. Is either a dict type or a IO type. - Default value is None. - :paramtype json: dict[str, JSON] or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/model-flatten/dictionary" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_dictionary_request(**kwargs: Any) -> HttpRequest: - """Get External Resource as a Dictionary. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/model-flatten/dictionary" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_resource_collection_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Put External Resource as a ResourceCollection. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: External Resource as a ResourceCollection to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "arrayofresources": [ - { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "p.name": "str", # Optional. - "provisioningState": "str", # Optional. - "provisioningStateValues": "str", # Optional. Known - values are: "Succeeded", "Failed", "canceled", "Accepted", - "Creating", "Created", "Updating", "Updated", "Deleting", "Deleted", - and "OK". - "type": "str" # Optional. - }, - "tags": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "type": "str" # Optional. Resource Type. - } - ], - "dictionaryofresources": { - "str": { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "p.name": "str", # Optional. Dictionary of - :code:``. - "provisioningState": "str", # Optional. Dictionary - of :code:``. - "provisioningStateValues": "str", # Optional. Known - values are: "Succeeded", "Failed", "canceled", "Accepted", - "Creating", "Created", "Updating", "Updated", "Deleting", "Deleted", - and "OK". - "type": "str" # Optional. Dictionary of - :code:``. - }, - "tags": { - "str": "str" # Optional. Dictionary of - :code:``. - }, - "type": "str" # Optional. Resource Type. - } - }, - "productresource": { - "id": "str", # Optional. Resource Id. - "location": "str", # Optional. Resource Location. - "name": "str", # Optional. Resource Name. - "properties": { - "p.name": "str", # Optional. Flattened product. - "provisioningState": "str", # Optional. Flattened product. - "provisioningStateValues": "str", # Optional. Known values - are: "Succeeded", "Failed", "canceled", "Accepted", "Creating", - "Created", "Updating", "Updated", "Deleting", "Deleted", and "OK". - "type": "str" # Optional. Flattened product. - }, - "tags": { - "str": "str" # Optional. Dictionary of :code:``. - }, - "type": "str" # Optional. Resource Type. - } - } - """ - - -@overload -def build_put_resource_collection_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Put External Resource as a ResourceCollection. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: External Resource as a ResourceCollection to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_resource_collection_request(**kwargs: Any) -> HttpRequest: - """Put External Resource as a ResourceCollection. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: External Resource as a ResourceCollection to put. Is either a model type or a IO - type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/model-flatten/resourcecollection" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_resource_collection_request(**kwargs: Any) -> HttpRequest: - """Get External Resource as a ResourceCollection. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/model-flatten/resourcecollection" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_simple_product_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Put Simple Product with client flattening true on the model. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Simple body product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "base_product_description": "str", # Optional. Description of product. - "base_product_id": "str", # Unique identifier representing a specific - product for a given latitude & longitude. For example, uberX in San Francisco - will have a different product_id than uberX in Los Angeles. Required. - "details": { - "max_product_capacity": "Large", # Default value is "Large". - Capacity of product. For example, 4 people. Required. - "max_product_display_name": "str", # Display name of product. - Required. - "max_product_image": { - "@odata.value": "str", # Optional. URL value. - "generic_value": "str" # Optional. Generic URL value. - } - } - } - """ - - -@overload -def build_put_simple_product_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Put Simple Product with client flattening true on the model. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Simple body product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_simple_product_request(**kwargs: Any) -> HttpRequest: - """Put Simple Product with client flattening true on the model. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Simple body product to put. Is either a model type or a IO type. Default value - is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/model-flatten/customFlattening" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_flattened_simple_product_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Put Flattened Simple Product with client flattening true on the parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Simple body product to post. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "base_product_description": "str", # Optional. Description of product. - "base_product_id": "str", # Unique identifier representing a specific - product for a given latitude & longitude. For example, uberX in San Francisco - will have a different product_id than uberX in Los Angeles. Required. - "details": { - "max_product_capacity": "Large", # Default value is "Large". - Capacity of product. For example, 4 people. Required. - "max_product_display_name": "str", # Display name of product. - Required. - "max_product_image": { - "@odata.value": "str", # Optional. URL value. - "generic_value": "str" # Optional. Generic URL value. - } - } - } - """ - - -@overload -def build_post_flattened_simple_product_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Put Flattened Simple Product with client flattening true on the parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Simple body product to post. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_flattened_simple_product_request(**kwargs: Any) -> HttpRequest: - """Put Flattened Simple Product with client flattening true on the parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Simple body product to post. Is either a model type or a IO type. Default value - is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/model-flatten/customFlattening" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_simple_product_with_grouping_request( - name: str, *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Put Simple Product with client flattening true on the model. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param name: Product name with value 'groupproduct'. Required. - :type name: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Simple body product to put. Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "base_product_description": "str", # Optional. Description of product. - "base_product_id": "str", # Unique identifier representing a specific - product for a given latitude & longitude. For example, uberX in San Francisco - will have a different product_id than uberX in Los Angeles. Required. - "details": { - "max_product_capacity": "Large", # Default value is "Large". - Capacity of product. For example, 4 people. Required. - "max_product_display_name": "str", # Display name of product. - Required. - "max_product_image": { - "@odata.value": "str", # Optional. URL value. - "generic_value": "str" # Optional. Generic URL value. - } - } - } - """ - - -@overload -def build_put_simple_product_with_grouping_request( - name: str, *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Put Simple Product with client flattening true on the model. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param name: Product name with value 'groupproduct'. Required. - :type name: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Simple body product to put. Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_simple_product_with_grouping_request(name: str, **kwargs: Any) -> HttpRequest: - """Put Simple Product with client flattening true on the model. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param name: Product name with value 'groupproduct'. Required. - :type name: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Simple body product to put. Is either a model type or a IO type. Default value - is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/model-flatten/customFlattening/parametergrouping/{name}/" - path_format_arguments = { - "name": _SERIALIZER.url("name", name, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/setup.py deleted file mode 100644 index 359d2091c31..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ModelFlatteningLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestresourceflatteningtestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestResourceFlatteningTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Resource Flattening for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/__init__.py deleted file mode 100644 index e8023e490a2..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import MultipleInheritanceServiceClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["MultipleInheritanceServiceClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_client.py deleted file mode 100644 index 83f160039cf..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import MultipleInheritanceServiceClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class MultipleInheritanceServiceClient: # pylint: disable=client-accepts-api-version-keyword - """Service client for multiinheritance client testing. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = MultipleInheritanceServiceClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `multipleinheritancelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from multipleinheritancelowlevel.rest import build_get_horse_request - >>> request = build_get_horse_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> MultipleInheritanceServiceClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_configuration.py deleted file mode 100644 index 9cce3269685..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class MultipleInheritanceServiceClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for MultipleInheritanceServiceClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(MultipleInheritanceServiceClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "multipleinheritanceserviceclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/__init__.py deleted file mode 100644 index 3337f737ce8..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import MultipleInheritanceServiceClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["MultipleInheritanceServiceClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_client.py deleted file mode 100644 index ccd211e0957..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import MultipleInheritanceServiceClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class MultipleInheritanceServiceClient: # pylint: disable=client-accepts-api-version-keyword - """Service client for multiinheritance client testing. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = MultipleInheritanceServiceClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `multipleinheritancelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from multipleinheritancelowlevel.rest import build_get_horse_request - >>> request = build_get_horse_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "MultipleInheritanceServiceClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_configuration.py deleted file mode 100644 index 8e8d260c441..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class MultipleInheritanceServiceClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for MultipleInheritanceServiceClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(MultipleInheritanceServiceClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "multipleinheritanceserviceclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/rest/__init__.py deleted file mode 100644 index 225e03c63e1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/rest/__init__.py +++ /dev/null @@ -1,31 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_horse_request -from ._request_builders import build_put_horse_request -from ._request_builders import build_get_pet_request -from ._request_builders import build_put_pet_request -from ._request_builders import build_get_feline_request -from ._request_builders import build_put_feline_request -from ._request_builders import build_get_cat_request -from ._request_builders import build_put_cat_request -from ._request_builders import build_get_kitten_request -from ._request_builders import build_put_kitten_request - -__all__ = [ - "build_get_horse_request", - "build_put_horse_request", - "build_get_pet_request", - "build_put_pet_request", - "build_get_feline_request", - "build_put_feline_request", - "build_get_cat_request", - "build_put_cat_request", - "build_get_kitten_request", - "build_put_kitten_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/rest/_request_builders.py deleted file mode 100644 index 065d7f88412..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/multipleinheritancelowlevel/rest/_request_builders.py +++ /dev/null @@ -1,564 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_horse_request(**kwargs: Any) -> HttpRequest: - """Get a horse with name 'Fred' and isAShowHorse true. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/multipleInheritance/horse" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_horse_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put a horse with name 'General' and isAShowHorse false. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Put a horse with name 'General' and isAShowHorse false. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "isAShowHorse": bool, # Optional. - "name": "str" # Required. - } - """ - - -@overload -def build_put_horse_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put a horse with name 'General' and isAShowHorse false. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Put a horse with name 'General' and isAShowHorse false. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_horse_request(**kwargs: Any) -> HttpRequest: - """Put a horse with name 'General' and isAShowHorse false. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Put a horse with name 'General' and isAShowHorse false. Is either a model type - or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/multipleInheritance/horse" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_pet_request(**kwargs: Any) -> HttpRequest: - """Get a pet with name 'Peanut'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/multipleInheritance/pet" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_pet_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put a pet with name 'Butter'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Put a pet with name 'Butter'. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "name": "str" # Required. - } - """ - - -@overload -def build_put_pet_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put a pet with name 'Butter'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Put a pet with name 'Butter'. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_pet_request(**kwargs: Any) -> HttpRequest: - """Put a pet with name 'Butter'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Put a pet with name 'Butter'. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/multipleInheritance/pet" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_feline_request(**kwargs: Any) -> HttpRequest: - """Get a feline where meows and hisses are true. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/multipleInheritance/feline" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_feline_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put a feline who hisses and doesn't meow. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Put a feline who hisses and doesn't meow. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "hisses": bool, # Optional. - "meows": bool # Optional. - } - """ - - -@overload -def build_put_feline_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put a feline who hisses and doesn't meow. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Put a feline who hisses and doesn't meow. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_feline_request(**kwargs: Any) -> HttpRequest: - """Put a feline who hisses and doesn't meow. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Put a feline who hisses and doesn't meow. Is either a model type or a IO type. - Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/multipleInheritance/feline" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_cat_request(**kwargs: Any) -> HttpRequest: - """Get a cat with name 'Whiskers' where likesMilk, meows, and hisses is true. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/multipleInheritance/cat" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_cat_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put a cat with name 'Boots' where likesMilk and hisses is false, meows is true. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Put a cat with name 'Boots' where likesMilk and hisses is false, meows is true. - Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "hisses": bool, # Optional. - "likesMilk": bool, # Optional. - "meows": bool, # Optional. - "name": "str" # Required. - } - """ - - -@overload -def build_put_cat_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put a cat with name 'Boots' where likesMilk and hisses is false, meows is true. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Put a cat with name 'Boots' where likesMilk and hisses is false, meows is - true. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_cat_request(**kwargs: Any) -> HttpRequest: - """Put a cat with name 'Boots' where likesMilk and hisses is false, meows is true. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Put a cat with name 'Boots' where likesMilk and hisses is false, meows is true. - Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/multipleInheritance/cat" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_get_kitten_request(**kwargs: Any) -> HttpRequest: - """Get a kitten with name 'Gatito' where likesMilk and meows is true, and hisses and eatsMiceYet - is false. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/multipleInheritance/kitten" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -@overload -def build_put_kitten_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put a kitten with name 'Kitty' where likesMilk and hisses is false, meows and eatsMiceYet is - true. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Put a kitten with name 'Kitty' where likesMilk and hisses is false, meows and - eatsMiceYet is true. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "eatsMiceYet": bool, # Optional. - "hisses": bool, # Optional. - "likesMilk": bool, # Optional. - "meows": bool, # Optional. - "name": "str" # Required. - } - """ - - -@overload -def build_put_kitten_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Put a kitten with name 'Kitty' where likesMilk and hisses is false, meows and eatsMiceYet is - true. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Put a kitten with name 'Kitty' where likesMilk and hisses is false, meows and - eatsMiceYet is true. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_put_kitten_request(**kwargs: Any) -> HttpRequest: - """Put a kitten with name 'Kitty' where likesMilk and hisses is false, meows and eatsMiceYet is - true. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Put a kitten with name 'Kitty' where likesMilk and hisses is false, meows and - eatsMiceYet is true. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/multipleInheritance/kitten" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/setup.py deleted file mode 100644 index eb50160820b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/MultipleInheritanceLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "multipleinheritanceserviceclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="MultipleInheritanceServiceClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Service client for multiinheritance client testing. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/__init__.py deleted file mode 100644 index c1b7b562457..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/__init__.py +++ /dev/null @@ -1,23 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = [] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/nooperationslowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/setup.py deleted file mode 100644 index 640c7abc69c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NoOperationsLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "nooperationsserviceclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="NoOperationsServiceClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Service client with no operations. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/__init__.py deleted file mode 100644 index 84774997821..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import NonStringEnumsClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["NonStringEnumsClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_client.py deleted file mode 100644 index 52c40562b08..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import NonStringEnumsClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class NonStringEnumsClient: # pylint: disable=client-accepts-api-version-keyword - """Testing non-string enums. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = NonStringEnumsClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `nonstringenumslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from nonstringenumslowlevel.rest import int - >>> request = int.build_put_request(json=json, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> NonStringEnumsClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_configuration.py deleted file mode 100644 index ee742dc5863..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class NonStringEnumsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for NonStringEnumsClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(NonStringEnumsClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "nonstringenumsclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/__init__.py deleted file mode 100644 index b60df58990e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import NonStringEnumsClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["NonStringEnumsClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_client.py deleted file mode 100644 index c037877d8c7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import NonStringEnumsClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class NonStringEnumsClient: # pylint: disable=client-accepts-api-version-keyword - """Testing non-string enums. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = NonStringEnumsClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `nonstringenumslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from nonstringenumslowlevel.rest import int - >>> request = int.build_put_request(json=json, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "NonStringEnumsClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_configuration.py deleted file mode 100644 index 148880bd3ec..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class NonStringEnumsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for NonStringEnumsClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(NonStringEnumsClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "nonstringenumsclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/float/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/float/__init__.py deleted file mode 100644 index 6bac485f11b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/float/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_put_request -from ._request_builders import build_get_request - -__all__ = [ - "build_put_request", - "build_get_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/float/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/float/_request_builders.py deleted file mode 100644 index 5ac06879437..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/float/_request_builders.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_put_request(*, json: Optional[float] = None, **kwargs: Any) -> HttpRequest: - """Put a float enum. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Input float enum. Known values are: 200.4, 403.4, 405.3, 406.2, and 429.1. - Default value is None. - :paramtype json: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/nonStringEnums/float/put" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_request(**kwargs: Any) -> HttpRequest: - """Get a float enum. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/nonStringEnums/float/get" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/int/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/int/__init__.py deleted file mode 100644 index 6bac485f11b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/int/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_put_request -from ._request_builders import build_get_request - -__all__ = [ - "build_put_request", - "build_get_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/int/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/int/_request_builders.py deleted file mode 100644 index 240b7ad223e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/nonstringenumslowlevel/rest/int/_request_builders.py +++ /dev/null @@ -1,72 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_put_request(*, json: Optional[int] = None, **kwargs: Any) -> HttpRequest: - """Put an int enum. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Input int enum. Known values are: 200, 403, 405, 406, and 429. Default value is - None. - :paramtype json: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/nonStringEnums/int/put" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_get_request(**kwargs: Any) -> HttpRequest: - """Get an int enum. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/nonStringEnums/int/get" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/setup.py deleted file mode 100644 index f6303331624..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/NonStringEnumsLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "nonstringenumsclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="NonStringEnumsClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Testing non-string enums. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/__init__.py deleted file mode 100644 index 8a5b25d57aa..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import ObjectTypeClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["ObjectTypeClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_client.py deleted file mode 100644 index c409a367eaa..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import ObjectTypeClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class ObjectTypeClient: # pylint: disable=client-accepts-api-version-keyword - """Service client for testing basic type: object swaggers. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = ObjectTypeClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `objecttypelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from objecttypelowlevel.rest import build_get_request - >>> request = build_get_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> ObjectTypeClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_configuration.py deleted file mode 100644 index 5a4c1636f8b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class ObjectTypeClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for ObjectTypeClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(ObjectTypeClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "objecttypeclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/__init__.py deleted file mode 100644 index 1b89958308d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import ObjectTypeClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["ObjectTypeClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_client.py deleted file mode 100644 index 7f6906154ae..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import ObjectTypeClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class ObjectTypeClient: # pylint: disable=client-accepts-api-version-keyword - """Service client for testing basic type: object swaggers. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = ObjectTypeClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `objecttypelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from objecttypelowlevel.rest import build_get_request - >>> request = build_get_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "ObjectTypeClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_configuration.py deleted file mode 100644 index 8e6db9a7d20..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class ObjectTypeClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for ObjectTypeClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(ObjectTypeClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "objecttypeclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/rest/__init__.py deleted file mode 100644 index 5c0124f9ae3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/rest/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_request -from ._request_builders import build_put_request - -__all__ = [ - "build_get_request", - "build_put_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/rest/_request_builders.py deleted file mode 100644 index 39ae299f51b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/objecttypelowlevel/rest/_request_builders.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_request(**kwargs: Any) -> HttpRequest: - """Basic get that returns an object. Returns object { 'message': 'An object was successfully - returned' }. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/objectType/get" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_request(*, json: JSON, **kwargs: Any) -> HttpRequest: - """Basic put that puts an object. Pass in {'foo': 'bar'} to get a 200 and anything else to get an - object error. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Pass in {'foo': 'bar'} for a 200, anything else for an object error. Required. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/objectType/put" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/setup.py deleted file mode 100644 index 2dc2938c9b3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ObjectTypeLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "objecttypeclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="ObjectTypeClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Service client for testing basic type: object swaggers. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/__init__.py deleted file mode 100644 index f7992f14496..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterFlattening -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterFlattening"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_client.py deleted file mode 100644 index 31d146fa54a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestParameterFlatteningConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterFlattening: # pylint: disable=client-accepts-api-version-keyword - """Resource Flattening for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestParameterFlatteningConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `parameterflatteninglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from parameterflatteninglowlevel.rest import availability_sets - >>> request = availability_sets.build_update_request(resource_group_name, avset, json=json, content_type=content_type, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestParameterFlattening - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_configuration.py deleted file mode 100644 index 3fe06c6bd8e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestParameterFlatteningConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterFlattening. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestParameterFlatteningConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestparameterflattening/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_vendor.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/__init__.py deleted file mode 100644 index 707ba968d8a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestParameterFlattening - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestParameterFlattening"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_client.py deleted file mode 100644 index a23042a18a7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestParameterFlatteningConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestParameterFlattening: # pylint: disable=client-accepts-api-version-keyword - """Resource Flattening for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestParameterFlatteningConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `parameterflatteninglowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from parameterflatteninglowlevel.rest import availability_sets - >>> request = availability_sets.build_update_request(resource_group_name, avset, json=json, content_type=content_type, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestParameterFlattening": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_configuration.py deleted file mode 100644 index 5bcb4b1198f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestParameterFlatteningConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestParameterFlattening. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestParameterFlatteningConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestparameterflattening/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/availability_sets/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/availability_sets/__init__.py deleted file mode 100644 index f4e2dd695ad..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/availability_sets/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_update_request - -__all__ = [ - "build_update_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/availability_sets/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/availability_sets/_request_builders.py deleted file mode 100644 index 11eeacdb49b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/parameterflatteninglowlevel/rest/availability_sets/_request_builders.py +++ /dev/null @@ -1,124 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -@overload -def build_update_request( - resource_group_name: str, avset: str, *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Updates the tags for an availability set. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group. Required. - :type resource_group_name: str - :param avset: The name of the storage availability set. Required. - :type avset: str - :keyword json: The tags. Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "tags": { - "str": "str" # A description about the set of tags. Required. - } - } - """ - - -@overload -def build_update_request( - resource_group_name: str, avset: str, *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Updates the tags for an availability set. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group. Required. - :type resource_group_name: str - :param avset: The name of the storage availability set. Required. - :type avset: str - :keyword content: The tags. Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_update_request(resource_group_name: str, avset: str, **kwargs: Any) -> HttpRequest: - """Updates the tags for an availability set. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: The name of the resource group. Required. - :type resource_group_name: str - :param avset: The name of the storage availability set. Required. - :type avset: str - :keyword json: The tags. Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/parameterFlattening/{resourceGroupName}/{availabilitySetName}" - path_format_arguments = { - "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), - "availabilitySetName": _SERIALIZER.url("avset", avset, "str", max_length=80), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PATCH", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/setup.py deleted file mode 100644 index 14eb3072ae2..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterFlatteningLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestparameterflattening" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestParameterFlattening", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Resource Flattening for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/__init__.py deleted file mode 100644 index abb93bca4ce..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import ParmaterizedEndpointClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["ParmaterizedEndpointClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_client.py deleted file mode 100644 index c85b59af023..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_client.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import ParmaterizedEndpointClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class ParmaterizedEndpointClient: # pylint: disable=client-accepts-api-version-keyword - """Service client for testing parameterized hosts with the name 'endpoint'. - - :param endpoint: The parameterized host. Pass in 'http://localhost:3000' to pass. Required. - :type endpoint: str - """ - - def __init__(self, endpoint: str, **kwargs: Any) -> None: - _endpoint = "{endpoint}" - self._config = ParmaterizedEndpointClientConfiguration(endpoint=endpoint, **kwargs) - self._client = PipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `parameterizedendpointlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from parameterizedendpointlowlevel.rest import build_get_request - >>> request = build_get_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> ParmaterizedEndpointClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_configuration.py deleted file mode 100644 index 70b9c7134ac..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_configuration.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class ParmaterizedEndpointClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for ParmaterizedEndpointClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The parameterized host. Pass in 'http://localhost:3000' to pass. Required. - :type endpoint: str - """ - - def __init__(self, endpoint: str, **kwargs: Any) -> None: - super(ParmaterizedEndpointClientConfiguration, self).__init__(**kwargs) - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "parmaterizedendpointclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/__init__.py deleted file mode 100644 index 896f4a37770..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import ParmaterizedEndpointClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["ParmaterizedEndpointClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_client.py deleted file mode 100644 index cbb700eae3f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_client.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import ParmaterizedEndpointClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class ParmaterizedEndpointClient: # pylint: disable=client-accepts-api-version-keyword - """Service client for testing parameterized hosts with the name 'endpoint'. - - :param endpoint: The parameterized host. Pass in 'http://localhost:3000' to pass. Required. - :type endpoint: str - """ - - def __init__(self, endpoint: str, **kwargs: Any) -> None: - _endpoint = "{endpoint}" - self._config = ParmaterizedEndpointClientConfiguration(endpoint=endpoint, **kwargs) - self._client = AsyncPipelineClient(base_url=_endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `parameterizedendpointlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from parameterizedendpointlowlevel.rest import build_get_request - >>> request = build_get_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - path_format_arguments = { - "endpoint": self._serialize.url("self._config.endpoint", self._config.endpoint, "str", skip_quote=True), - } - - request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "ParmaterizedEndpointClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_configuration.py deleted file mode 100644 index 9b5d40918f1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_configuration.py +++ /dev/null @@ -1,45 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class ParmaterizedEndpointClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for ParmaterizedEndpointClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param endpoint: The parameterized host. Pass in 'http://localhost:3000' to pass. Required. - :type endpoint: str - """ - - def __init__(self, endpoint: str, **kwargs: Any) -> None: - super(ParmaterizedEndpointClientConfiguration, self).__init__(**kwargs) - if endpoint is None: - raise ValueError("Parameter 'endpoint' must not be None.") - - self.endpoint = endpoint - kwargs.setdefault("sdk_moniker", "parmaterizedendpointclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/rest/__init__.py deleted file mode 100644 index e17bdb605ab..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/rest/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_request - -__all__ = [ - "build_get_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/rest/_request_builders.py deleted file mode 100644 index 7100bd5f435..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/parameterizedendpointlowlevel/rest/_request_builders.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest - -from .._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_request(**kwargs: Any) -> HttpRequest: - """Basic get to make sure base url formatting of 'endpoint' works. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/parameterizedEndpoint/get" - - return HttpRequest(method="GET", url=_url, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/setup.py deleted file mode 100644 index 4858f6e2d3a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ParameterizedEndpointLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "parmaterizedendpointclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="ParmaterizedEndpointClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Service client for testing parameterized hosts with the name 'endpoint'. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/__init__.py deleted file mode 100644 index 945740e6772..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestReportService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestReportService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_client.py deleted file mode 100644 index 3b55382f5ce..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestReportServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestReportService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestReportServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `reportlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from reportlowlevel.rest import build_get_report_request - >>> request = build_get_report_request(qualifier=qualifier, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestReportService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_configuration.py deleted file mode 100644 index ffc083a4bc1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestReportServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestReportService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestReportServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestreportservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/__init__.py deleted file mode 100644 index df63f6cc127..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestReportService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestReportService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_client.py deleted file mode 100644 index f3c4856dd1d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestReportServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestReportService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestReportServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `reportlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from reportlowlevel.rest import build_get_report_request - >>> request = build_get_report_request(qualifier=qualifier, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestReportService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_configuration.py deleted file mode 100644 index deffe2972cc..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestReportServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestReportService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestReportServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestreportservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/rest/__init__.py deleted file mode 100644 index 5d705ae4de1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/rest/__init__.py +++ /dev/null @@ -1,15 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_report_request -from ._request_builders import build_get_optional_report_request - -__all__ = [ - "build_get_report_request", - "build_get_optional_report_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/rest/_request_builders.py deleted file mode 100644 index 21e944d8ae8..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/reportlowlevel/rest/_request_builders.py +++ /dev/null @@ -1,84 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_report_request(*, qualifier: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Get test coverage report. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword qualifier: If specified, qualifies the generated report further (e.g. '2.7' vs '3.5' - in for Python). The only effect is, that generators that run all tests several times, can - distinguish the generated reports. Default value is None. - :paramtype qualifier: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/report" - - # Construct parameters - if qualifier is not None: - _params["qualifier"] = _SERIALIZER.query("qualifier", qualifier, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_optional_report_request(*, qualifier: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Get optional test coverage report. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword qualifier: If specified, qualifies the generated report further (e.g. '2.7' vs '3.5' - in for Python). The only effect is, that generators that run all tests several times, can - distinguish the generated reports. Default value is None. - :paramtype qualifier: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/report/optional" - - # Construct parameters - if qualifier is not None: - _params["qualifier"] = _SERIALIZER.query("qualifier", qualifier, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/setup.py deleted file mode 100644 index 669a633f4c0..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReportLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestreportservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestReportService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/__init__.py deleted file mode 100644 index 940107b4a73..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestRequiredOptionalTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestRequiredOptionalTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_client.py deleted file mode 100644 index d0f52654307..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_client.py +++ /dev/null @@ -1,93 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestRequiredOptionalTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestRequiredOptionalTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param required_global_path: number of items to skip. Required. - :type required_global_path: str - :param required_global_query: number of items to skip. Required. - :type required_global_query: str - :param optional_global_query: number of items to skip. Default value is None. - :type optional_global_query: int - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, - required_global_path: str, - required_global_query: str, - optional_global_query: Optional[int] = None, - *, - endpoint: str = "http://localhost:3000", - **kwargs: Any - ) -> None: - self._config = AutoRestRequiredOptionalTestServiceConfiguration( - required_global_path=required_global_path, - required_global_query=required_global_query, - optional_global_query=optional_global_query, - **kwargs - ) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `requiredoptionallowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from requiredoptionallowlevel.rest import implicit - >>> request = implicit.build_get_required_path_request(path_parameter, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestRequiredOptionalTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_configuration.py deleted file mode 100644 index 6161e2a2e80..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_configuration.py +++ /dev/null @@ -1,62 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestRequiredOptionalTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestRequiredOptionalTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param required_global_path: number of items to skip. Required. - :type required_global_path: str - :param required_global_query: number of items to skip. Required. - :type required_global_query: str - :param optional_global_query: number of items to skip. Default value is None. - :type optional_global_query: int - """ - - def __init__( - self, - required_global_path: str, - required_global_query: str, - optional_global_query: Optional[int] = None, - **kwargs: Any - ) -> None: - super(AutoRestRequiredOptionalTestServiceConfiguration, self).__init__(**kwargs) - if required_global_path is None: - raise ValueError("Parameter 'required_global_path' must not be None.") - if required_global_query is None: - raise ValueError("Parameter 'required_global_query' must not be None.") - - self.required_global_path = required_global_path - self.required_global_query = required_global_query - self.optional_global_query = optional_global_query - kwargs.setdefault("sdk_moniker", "autorestrequiredoptionaltestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_vendor.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/__init__.py deleted file mode 100644 index f802e3b7d1c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestRequiredOptionalTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestRequiredOptionalTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_client.py deleted file mode 100644 index 32ef9509a67..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_client.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestRequiredOptionalTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestRequiredOptionalTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param required_global_path: number of items to skip. Required. - :type required_global_path: str - :param required_global_query: number of items to skip. Required. - :type required_global_query: str - :param optional_global_query: number of items to skip. Default value is None. - :type optional_global_query: int - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, - required_global_path: str, - required_global_query: str, - optional_global_query: Optional[int] = None, - *, - endpoint: str = "http://localhost:3000", - **kwargs: Any - ) -> None: - self._config = AutoRestRequiredOptionalTestServiceConfiguration( - required_global_path=required_global_path, - required_global_query=required_global_query, - optional_global_query=optional_global_query, - **kwargs - ) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `requiredoptionallowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from requiredoptionallowlevel.rest import implicit - >>> request = implicit.build_get_required_path_request(path_parameter, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestRequiredOptionalTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_configuration.py deleted file mode 100644 index 70aacbbfe65..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_configuration.py +++ /dev/null @@ -1,59 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestRequiredOptionalTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestRequiredOptionalTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param required_global_path: number of items to skip. Required. - :type required_global_path: str - :param required_global_query: number of items to skip. Required. - :type required_global_query: str - :param optional_global_query: number of items to skip. Default value is None. - :type optional_global_query: int - """ - - def __init__( - self, - required_global_path: str, - required_global_query: str, - optional_global_query: Optional[int] = None, - **kwargs: Any - ) -> None: - super(AutoRestRequiredOptionalTestServiceConfiguration, self).__init__(**kwargs) - if required_global_path is None: - raise ValueError("Parameter 'required_global_path' must not be None.") - if required_global_query is None: - raise ValueError("Parameter 'required_global_query' must not be None.") - - self.required_global_path = required_global_path - self.required_global_query = required_global_query - self.optional_global_query = optional_global_query - kwargs.setdefault("sdk_moniker", "autorestrequiredoptionaltestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/explicit/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/explicit/__init__.py deleted file mode 100644 index 505873cfc54..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/explicit/__init__.py +++ /dev/null @@ -1,59 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_put_optional_binary_body_request -from ._request_builders import build_put_required_binary_body_request -from ._request_builders import build_post_required_integer_parameter_request -from ._request_builders import build_post_optional_integer_parameter_request -from ._request_builders import build_post_required_integer_property_request -from ._request_builders import build_post_optional_integer_property_request -from ._request_builders import build_post_required_integer_header_request -from ._request_builders import build_post_optional_integer_header_request -from ._request_builders import build_post_required_string_parameter_request -from ._request_builders import build_post_optional_string_parameter_request -from ._request_builders import build_post_required_string_property_request -from ._request_builders import build_post_optional_string_property_request -from ._request_builders import build_post_required_string_header_request -from ._request_builders import build_post_optional_string_header_request -from ._request_builders import build_post_required_class_parameter_request -from ._request_builders import build_post_optional_class_parameter_request -from ._request_builders import build_post_required_class_property_request -from ._request_builders import build_post_optional_class_property_request -from ._request_builders import build_post_required_array_parameter_request -from ._request_builders import build_post_optional_array_parameter_request -from ._request_builders import build_post_required_array_property_request -from ._request_builders import build_post_optional_array_property_request -from ._request_builders import build_post_required_array_header_request -from ._request_builders import build_post_optional_array_header_request - -__all__ = [ - "build_put_optional_binary_body_request", - "build_put_required_binary_body_request", - "build_post_required_integer_parameter_request", - "build_post_optional_integer_parameter_request", - "build_post_required_integer_property_request", - "build_post_optional_integer_property_request", - "build_post_required_integer_header_request", - "build_post_optional_integer_header_request", - "build_post_required_string_parameter_request", - "build_post_optional_string_parameter_request", - "build_post_required_string_property_request", - "build_post_optional_string_property_request", - "build_post_required_string_header_request", - "build_post_optional_string_header_request", - "build_post_required_class_parameter_request", - "build_post_optional_class_parameter_request", - "build_post_required_class_property_request", - "build_post_optional_class_property_request", - "build_post_required_array_parameter_request", - "build_post_optional_array_parameter_request", - "build_post_required_array_property_request", - "build_post_optional_array_property_request", - "build_post_required_array_header_request", - "build_post_optional_array_header_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/explicit/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/explicit/_request_builders.py deleted file mode 100644 index 471d8f34db6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/explicit/_request_builders.py +++ /dev/null @@ -1,1407 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, List, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_put_optional_binary_body_request(*, content: Optional[IO] = None, **kwargs: Any) -> HttpRequest: - """Test explicitly optional body parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/explicit/optional/binary-body" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_put_required_binary_body_request(*, content: IO, **kwargs: Any) -> HttpRequest: - """Test explicitly required body parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/explicit/required/binary-body" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_post_required_integer_parameter_request(*, json: int, **kwargs: Any) -> HttpRequest: - """Test explicitly required integer. Please put null and the client library should throw before - the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/requied/integer/parameter" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -def build_post_optional_integer_parameter_request(*, json: Optional[int] = None, **kwargs: Any) -> HttpRequest: - """Test explicitly optional integer. Please put null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Default value is None. - :paramtype json: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/optional/integer/parameter" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, json=json, **kwargs) - - -@overload -def build_post_required_integer_property_request( - *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required integer. Please put a valid int-wrapper with 'value' = null and the - client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "value": 0 # Required. - } - """ - - -@overload -def build_post_required_integer_property_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required integer. Please put a valid int-wrapper with 'value' = null and the - client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_required_integer_property_request(**kwargs: Any) -> HttpRequest: - """Test explicitly required integer. Please put a valid int-wrapper with 'value' = null and the - client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/requied/integer/property" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_optional_integer_property_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional integer. Please put a valid int-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "value": 0 # Optional. - } - """ - - -@overload -def build_post_optional_integer_property_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional integer. Please put a valid int-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_optional_integer_property_request(**kwargs: Any) -> HttpRequest: - """Test explicitly optional integer. Please put a valid int-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/optional/integer/property" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_required_integer_header_request(*, header_parameter: int, **kwargs: Any) -> HttpRequest: - """Test explicitly required integer. Please put a header 'headerParameter' => null and the client - library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword header_parameter: Required. - :paramtype header_parameter: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/requied/integer/header" - - # Construct headers - _headers["headerParameter"] = _SERIALIZER.header("header_parameter", header_parameter, "int") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_optional_integer_header_request(*, header_parameter: Optional[int] = None, **kwargs: Any) -> HttpRequest: - """Test explicitly optional integer. Please put a header 'headerParameter' => null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword header_parameter: Default value is None. - :paramtype header_parameter: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/optional/integer/header" - - # Construct headers - if header_parameter is not None: - _headers["headerParameter"] = _SERIALIZER.header("header_parameter", header_parameter, "int") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_required_string_parameter_request(*, content: str, **kwargs: Any) -> HttpRequest: - """Test explicitly required string. Please put null and the client library should throw before the - request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/requied/string/parameter" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, content=content, **kwargs) - - -def build_post_optional_string_parameter_request(*, content: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Test explicitly optional string. Please put null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Default value is None. - :paramtype content: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/optional/string/parameter" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, content=content, **kwargs) - - -@overload -def build_post_required_string_property_request( - *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required string. Please put a valid string-wrapper with 'value' = null and the - client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "value": "str" # Required. - } - """ - - -@overload -def build_post_required_string_property_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required string. Please put a valid string-wrapper with 'value' = null and the - client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_required_string_property_request(**kwargs: Any) -> HttpRequest: - """Test explicitly required string. Please put a valid string-wrapper with 'value' = null and the - client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/requied/string/property" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_optional_string_property_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional integer. Please put a valid string-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "value": "str" # Optional. - } - """ - - -@overload -def build_post_optional_string_property_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional integer. Please put a valid string-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_optional_string_property_request(**kwargs: Any) -> HttpRequest: - """Test explicitly optional integer. Please put a valid string-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/optional/string/property" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_required_string_header_request(*, header_parameter: str, **kwargs: Any) -> HttpRequest: - """Test explicitly required string. Please put a header 'headerParameter' => null and the client - library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword header_parameter: Required. - :paramtype header_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/requied/string/header" - - # Construct headers - _headers["headerParameter"] = _SERIALIZER.header("header_parameter", header_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_optional_string_header_request(*, body_parameter: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Test explicitly optional string. Please put a header 'headerParameter' => null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword body_parameter: Default value is None. - :paramtype body_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/optional/string/header" - - # Construct headers - if body_parameter is not None: - _headers["bodyParameter"] = _SERIALIZER.header("body_parameter", body_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_required_class_parameter_request( - *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required complex object. Please put null and the client library should throw - before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": 0, # Required. - "name": "str" # Optional. - } - """ - - -@overload -def build_post_required_class_parameter_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required complex object. Please put null and the client library should throw - before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_required_class_parameter_request(**kwargs: Any) -> HttpRequest: - """Test explicitly required complex object. Please put null and the client library should throw - before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/requied/class/parameter" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_optional_class_parameter_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional complex object. Please put null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": 0, # Required. - "name": "str" # Optional. - } - """ - - -@overload -def build_post_optional_class_parameter_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional complex object. Please put null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_optional_class_parameter_request(**kwargs: Any) -> HttpRequest: - """Test explicitly optional complex object. Please put null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/optional/class/parameter" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_required_class_property_request( - *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required complex object. Please put a valid class-wrapper with 'value' = null - and the client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "value": { - "id": 0, # Required. - "name": "str" # Optional. Required. - } - } - """ - - -@overload -def build_post_required_class_property_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required complex object. Please put a valid class-wrapper with 'value' = null - and the client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_required_class_property_request(**kwargs: Any) -> HttpRequest: - """Test explicitly required complex object. Please put a valid class-wrapper with 'value' = null - and the client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/requied/class/property" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_optional_class_property_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional complex object. Please put a valid class-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "value": { - "id": 0, # Required. - "name": "str" # Optional. - } - } - """ - - -@overload -def build_post_optional_class_property_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional complex object. Please put a valid class-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_optional_class_property_request(**kwargs: Any) -> HttpRequest: - """Test explicitly optional complex object. Please put a valid class-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/optional/class/property" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_required_array_parameter_request( - *, json: List[str], content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required array. Please put null and the client library should throw before the - request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: list[str] - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - "str" # Optional. - ] - """ - - -@overload -def build_post_required_array_parameter_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required array. Please put null and the client library should throw before the - request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_required_array_parameter_request(**kwargs: Any) -> HttpRequest: - """Test explicitly required array. Please put null and the client library should throw before the - request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a list type or a IO type. Required. - :paramtype json: list[str] or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/requied/array/parameter" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_optional_array_parameter_request( - *, content_type: Optional[str] = None, json: Optional[List[str]] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional array. Please put null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Default value is None. - :paramtype json: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = [ - "str" # Optional. - ] - """ - - -@overload -def build_post_optional_array_parameter_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional array. Please put null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_optional_array_parameter_request(**kwargs: Any) -> HttpRequest: - """Test explicitly optional array. Please put null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Is either a list type or a IO type. Default value is None. - :paramtype json: list[str] or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/optional/array/parameter" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_required_array_property_request( - *, json: JSON, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required array. Please put a valid array-wrapper with 'value' = null and the - client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "value": [ - "str" # Required. - ] - } - """ - - -@overload -def build_post_required_array_property_request( - *, content: IO, content_type: Optional[str] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly required array. Please put a valid array-wrapper with 'value' = null and the - client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_required_array_property_request(**kwargs: Any) -> HttpRequest: - """Test explicitly required array. Please put a valid array-wrapper with 'value' = null and the - client library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/requied/array/property" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -@overload -def build_post_optional_array_property_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional array. Please put a valid array-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "value": [ - "str" # Optional. - ] - } - """ - - -@overload -def build_post_optional_array_property_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional array. Please put a valid array-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_optional_array_property_request(**kwargs: Any) -> HttpRequest: - """Test explicitly optional array. Please put a valid array-wrapper with 'value' = null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/optional/array/property" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_required_array_header_request(*, header_parameter: List[str], **kwargs: Any) -> HttpRequest: - """Test explicitly required array. Please put a header 'headerParameter' => null and the client - library should throw before the request is sent. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword header_parameter: Required. - :paramtype header_parameter: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/requied/array/header" - - # Construct headers - _headers["headerParameter"] = _SERIALIZER.header("header_parameter", header_parameter, "[str]", div=",") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_post_optional_array_header_request( - *, header_parameter: Optional[List[str]] = None, **kwargs: Any -) -> HttpRequest: - """Test explicitly optional integer. Please put a header 'headerParameter' => null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword header_parameter: Default value is None. - :paramtype header_parameter: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/optional/array/header" - - # Construct headers - if header_parameter is not None: - _headers["headerParameter"] = _SERIALIZER.header("header_parameter", header_parameter, "[str]", div=",") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/implicit/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/implicit/__init__.py deleted file mode 100644 index 54b9c8be42e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/implicit/__init__.py +++ /dev/null @@ -1,27 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_required_path_request -from ._request_builders import build_put_optional_query_request -from ._request_builders import build_put_optional_header_request -from ._request_builders import build_put_optional_body_request -from ._request_builders import build_put_optional_binary_body_request -from ._request_builders import build_get_required_global_path_request -from ._request_builders import build_get_required_global_query_request -from ._request_builders import build_get_optional_global_query_request - -__all__ = [ - "build_get_required_path_request", - "build_put_optional_query_request", - "build_put_optional_header_request", - "build_put_optional_body_request", - "build_put_optional_binary_body_request", - "build_get_required_global_path_request", - "build_get_required_global_query_request", - "build_get_optional_global_query_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/implicit/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/implicit/_request_builders.py deleted file mode 100644 index 6c4ba1f8528..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/requiredoptionallowlevel/rest/implicit/_request_builders.py +++ /dev/null @@ -1,267 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, IO, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_required_path_request(path_parameter: str, **kwargs: Any) -> HttpRequest: - """Test implicitly required path parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param path_parameter: Required. - :type path_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/implicit/required/path/{pathParameter}" - path_format_arguments = { - "pathParameter": _SERIALIZER.url("path_parameter", path_parameter, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_optional_query_request(*, query_parameter: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Test implicitly optional query parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword query_parameter: Default value is None. - :paramtype query_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/implicit/optional/query" - - # Construct parameters - if query_parameter is not None: - _params["queryParameter"] = _SERIALIZER.query("query_parameter", query_parameter, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_put_optional_header_request(*, query_parameter: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Test implicitly optional header parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword query_parameter: Default value is None. - :paramtype query_parameter: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/implicit/optional/header" - - # Construct headers - if query_parameter is not None: - _headers["queryParameter"] = _SERIALIZER.header("query_parameter", query_parameter, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_put_optional_body_request(*, content: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Test implicitly optional body parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Default value is None. - :paramtype content: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/implicit/optional/body" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_put_optional_binary_body_request(*, content: Optional[IO] = None, **kwargs: Any) -> HttpRequest: - """Test implicitly optional body parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/implicit/optional/binary-body" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_required_global_path_request(required_global_path: str, **kwargs: Any) -> HttpRequest: - """Test implicitly required path parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param required_global_path: number of items to skip. Required. - :type required_global_path: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/global/required/path/{required-global-path}" - path_format_arguments = { - "required-global-path": _SERIALIZER.url("required_global_path", required_global_path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_required_global_query_request(*, required_global_query: str, **kwargs: Any) -> HttpRequest: - """Test implicitly required query parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword required_global_query: number of items to skip. Required. - :paramtype required_global_query: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/global/required/query" - - # Construct parameters - _params["required-global-query"] = _SERIALIZER.query("required_global_query", required_global_query, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_optional_global_query_request( - *, optional_global_query: Optional[int] = None, **kwargs: Any -) -> HttpRequest: - """Test implicitly optional query parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword optional_global_query: number of items to skip. Default value is None. - :paramtype optional_global_query: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reqopt/global/optional/query" - - # Construct parameters - if optional_global_query is not None: - _params["optional-global-query"] = _SERIALIZER.query("optional_global_query", optional_global_query, "int") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/setup.py deleted file mode 100644 index 45ceb1cfd1a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/RequiredOptionalLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestrequiredoptionaltestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestRequiredOptionalTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/__init__.py deleted file mode 100644 index e8a0b61fba2..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import ReservedWordsClient -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["ReservedWordsClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_client.py deleted file mode 100644 index 0f37d46d273..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import ReservedWordsClientConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class ReservedWordsClient: # pylint: disable=client-accepts-api-version-keyword - """Swagger that has operation groups etc. with reserved words. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = ReservedWordsClientConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `reservedwordslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from reservedwordslowlevel.rest import import_operations - >>> request = import_operations.build_operation_one_request(parameter1=parameter1, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> ReservedWordsClient - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_configuration.py deleted file mode 100644 index e6f40d7e00e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class ReservedWordsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for ReservedWordsClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(ReservedWordsClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "reservedwordsclient/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_vendor.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/__init__.py deleted file mode 100644 index ab1577141d2..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import ReservedWordsClient - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["ReservedWordsClient"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_client.py deleted file mode 100644 index ad7b983740f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import ReservedWordsClientConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class ReservedWordsClient: # pylint: disable=client-accepts-api-version-keyword - """Swagger that has operation groups etc. with reserved words. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = ReservedWordsClientConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `reservedwordslowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from reservedwordslowlevel.rest import import_operations - >>> request = import_operations.build_operation_one_request(parameter1=parameter1, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "ReservedWordsClient": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_configuration.py deleted file mode 100644 index 14375a5d2f6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class ReservedWordsClientConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for ReservedWordsClient. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(ReservedWordsClientConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "reservedwordsclient/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/__init__.py deleted file mode 100644 index 778adf8941b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_operation_with_content_param_request -from ._request_builders import build_operation_with_json_param_request -from ._request_builders import build_operation_with_data_param_request -from ._request_builders import build_operation_with_files_param_request -from ._request_builders import build_operation_with_url_request - -__all__ = [ - "build_operation_with_content_param_request", - "build_operation_with_json_param_request", - "build_operation_with_data_param_request", - "build_operation_with_files_param_request", - "build_operation_with_url_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/_request_builders.py deleted file mode 100644 index 8fcc00d675f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/_request_builders.py +++ /dev/null @@ -1,198 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, IO, List, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer -from .._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_operation_with_content_param_request(*, content: IO, **kwargs: Any) -> HttpRequest: - """Operation with body param called content. Pass in b'hello, world'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Pass in b'hello, world'. Required. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reservedWords/operation/content" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_operation_with_json_param_request(*, json: Any, **kwargs: Any) -> HttpRequest: - """Operation with body param called 'json'. Pass in {'hello': 'world'}. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Pass in {'hello': 'world'}. Required. - :paramtype json: any - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reservedWords/operation/json" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, json=json, **kwargs) - - -def build_operation_with_data_param_request(**kwargs: Any) -> HttpRequest: - """Operation with urlencoded body param called 'data'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - data = { - "str": {} # Optional. - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reservedWords/operation/data" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_operation_with_files_param_request(**kwargs: Any) -> HttpRequest: - """Operation with multipart body param called 'files'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - files = { - "str": {} # Optional. - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reservedWords/operation/files" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_operation_with_url_request( - url: str, *, header_parameters: str, query_parameters: Optional[List[str]] = None, **kwargs: Any -) -> HttpRequest: - """Operation with path format argument URL, header param headerParameters, and query param - queryParameters. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param url: Pass in 'foo'. Required. - :type url: str - :keyword header_parameters: Header arg that uses same name as headerParameters in generated - code. Pass in 'x-ms-header' to pass. Required. - :paramtype header_parameters: str - :keyword query_parameters: Query args that uses same name as queryParameters in generated code. - Pass in ['one', 'two'] to pass test. Default value is None. - :paramtype query_parameters: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reservedWords/{url}" - path_format_arguments = { - "url": _SERIALIZER.url("url", url, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - if query_parameters is not None: - _params["queryParameters"] = [ - _SERIALIZER.query("query_parameters", q, "str") if q is not None else "" for q in query_parameters - ] - - # Construct headers - _headers["headerParameters"] = _SERIALIZER.header("header_parameters", header_parameters, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/import_operations/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/import_operations/__init__.py deleted file mode 100644 index 9faef03b506..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/import_operations/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_operation_one_request - -__all__ = [ - "build_operation_one_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/import_operations/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/import_operations/_request_builders.py deleted file mode 100644 index 06be630c185..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/reservedwordslowlevel/rest/import_operations/_request_builders.py +++ /dev/null @@ -1,47 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_operation_one_request(*, parameter1: str, **kwargs: Any) -> HttpRequest: - """Operation in operation group import, a reserved word. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword parameter1: Pass in 'foo' to pass this test. Required. - :paramtype parameter1: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/reservedWords/operationGroup/import" - - # Construct parameters - _params["parameter1"] = _SERIALIZER.query("parameter1", parameter1, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/setup.py deleted file mode 100644 index 7f0877e8342..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ReservedWordsLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "reservedwordsclient" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="ReservedWordsClient", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Swagger that has operation groups etc. with reserved words. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/__init__.py deleted file mode 100644 index fc67379a315..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutorestSecurityAad -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutorestSecurityAad"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_client.py deleted file mode 100644 index d1f30d84bf6..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_client.py +++ /dev/null @@ -1,80 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutorestSecurityAadConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials import TokenCredential - - -class AutorestSecurityAad: # pylint: disable=client-accepts-api-version-keyword - """Autorest Security Aad REST APIs. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, credential: "TokenCredential", *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - self._config = AutorestSecurityAadConfiguration(credential=credential, **kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `securityaadswaggerlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from securityaadswaggerlowlevel.rest import build_head_request - >>> request = build_head_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutorestSecurityAad - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_configuration.py deleted file mode 100644 index 9f6a326645f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_configuration.py +++ /dev/null @@ -1,57 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials import TokenCredential - - -class AutorestSecurityAadConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutorestSecurityAad. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.TokenCredential - """ - - def __init__(self, credential: "TokenCredential", **kwargs: Any) -> None: - super(AutorestSecurityAadConfiguration, self).__init__(**kwargs) - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.credential = credential - self.credential_scopes = kwargs.pop("credential_scopes", ["https://security.microsoft.com/.default"]) - kwargs.setdefault("sdk_moniker", "autorestsecurityaad/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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 = policies.BearerTokenCredentialPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/__init__.py deleted file mode 100644 index 5d1e5f0e256..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutorestSecurityAad - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutorestSecurityAad"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_client.py deleted file mode 100644 index 409ea4cda7e..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_client.py +++ /dev/null @@ -1,77 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutorestSecurityAadConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - from azure.core.credentials_async import AsyncTokenCredential - - -class AutorestSecurityAad: # pylint: disable=client-accepts-api-version-keyword - """Autorest Security Aad REST APIs. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, credential: "AsyncTokenCredential", *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - self._config = AutorestSecurityAadConfiguration(credential=credential, **kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `securityaadswaggerlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from securityaadswaggerlowlevel.rest import build_head_request - >>> request = build_head_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutorestSecurityAad": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_configuration.py deleted file mode 100644 index 3699522524f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_configuration.py +++ /dev/null @@ -1,54 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, TYPE_CHECKING - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from azure.core.credentials_async import AsyncTokenCredential - - -class AutorestSecurityAadConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutorestSecurityAad. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials_async.AsyncTokenCredential - """ - - def __init__(self, credential: "AsyncTokenCredential", **kwargs: Any) -> None: - super(AutorestSecurityAadConfiguration, self).__init__(**kwargs) - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.credential = credential - self.credential_scopes = kwargs.pop("credential_scopes", ["https://security.microsoft.com/.default"]) - kwargs.setdefault("sdk_moniker", "autorestsecurityaad/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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 = policies.AsyncBearerTokenCredentialPolicy( - self.credential, *self.credential_scopes, **kwargs - ) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/rest/__init__.py deleted file mode 100644 index c348ad5916d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/rest/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_head_request - -__all__ = [ - "build_head_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/rest/_request_builders.py deleted file mode 100644 index b76dcc7f032..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/securityaadswaggerlowlevel/rest/_request_builders.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest - -from .._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_head_request(**kwargs: Any) -> HttpRequest: - """Operation. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/securityaad" - - return HttpRequest(method="HEAD", url=_url, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/setup.py deleted file mode 100644 index bce24afdcbc..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityAadSwaggerLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestsecurityaad" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutorestSecurityAad", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Autorest Security Aad REST APIs. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/__init__.py deleted file mode 100644 index 1f63bc21d2d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutorestSecurityKey -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutorestSecurityKey"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_client.py deleted file mode 100644 index eb0225cad83..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_client.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.credentials import AzureKeyCredential -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutorestSecurityKeyConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutorestSecurityKey: # pylint: disable=client-accepts-api-version-keyword - """Autorest Security Key REST APIs. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, credential: AzureKeyCredential, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - self._config = AutorestSecurityKeyConfiguration(credential=credential, **kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `securitykeyswaggerlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from securitykeyswaggerlowlevel.rest import build_head_request - >>> request = build_head_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutorestSecurityKey - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_configuration.py deleted file mode 100644 index ace6991197d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_configuration.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.credentials import AzureKeyCredential -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutorestSecurityKeyConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutorestSecurityKey. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - """ - - def __init__(self, credential: AzureKeyCredential, **kwargs: Any) -> None: - super(AutorestSecurityKeyConfiguration, self).__init__(**kwargs) - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.credential = credential - kwargs.setdefault("sdk_moniker", "autorestsecuritykey/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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 = policies.AzureKeyCredentialPolicy(self.credential, "security-key", **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/__init__.py deleted file mode 100644 index ccb6c54c2df..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutorestSecurityKey - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutorestSecurityKey"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_client.py deleted file mode 100644 index a740991e698..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_client.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.credentials import AzureKeyCredential -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutorestSecurityKeyConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutorestSecurityKey: # pylint: disable=client-accepts-api-version-keyword - """Autorest Security Key REST APIs. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, credential: AzureKeyCredential, *, endpoint: str = "http://localhost:3000", **kwargs: Any - ) -> None: - self._config = AutorestSecurityKeyConfiguration(credential=credential, **kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `securitykeyswaggerlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from securitykeyswaggerlowlevel.rest import build_head_request - >>> request = build_head_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutorestSecurityKey": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_configuration.py deleted file mode 100644 index 8215db758b3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_configuration.py +++ /dev/null @@ -1,48 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.credentials import AzureKeyCredential -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutorestSecurityKeyConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutorestSecurityKey. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param credential: Credential needed for the client to connect to Azure. Required. - :type credential: ~azure.core.credentials.AzureKeyCredential - """ - - def __init__(self, credential: AzureKeyCredential, **kwargs: Any) -> None: - super(AutorestSecurityKeyConfiguration, self).__init__(**kwargs) - if credential is None: - raise ValueError("Parameter 'credential' must not be None.") - - self.credential = credential - kwargs.setdefault("sdk_moniker", "autorestsecuritykey/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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 = policies.AzureKeyCredentialPolicy(self.credential, "security-key", **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/rest/__init__.py deleted file mode 100644 index c348ad5916d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/rest/__init__.py +++ /dev/null @@ -1,13 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_head_request - -__all__ = [ - "build_head_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/rest/_request_builders.py deleted file mode 100644 index bde3243d61c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/securitykeyswaggerlowlevel/rest/_request_builders.py +++ /dev/null @@ -1,33 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest - -from .._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_head_request(**kwargs: Any) -> HttpRequest: - """Operation. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/securitykey" - - return HttpRequest(method="HEAD", url=_url, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/setup.py deleted file mode 100644 index 235c90c90bc..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/SecurityKeySwaggerLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestsecuritykey" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutorestSecurityKey", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Autorest Security Key REST APIs. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/setup.py deleted file mode 100644 index 0e09cbf23d1..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autoresturltestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestUrlTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/__init__.py deleted file mode 100644 index 6c9005c3f3f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestUrlTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestUrlTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_client.py deleted file mode 100644 index 311c73da8e2..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_client.py +++ /dev/null @@ -1,88 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Optional, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestUrlTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestUrlTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param global_string_path: A string value 'globalItemStringPath' that appears in the path. - Required. - :type global_string_path: str - :param global_string_query: should contain value null. Default value is None. - :type global_string_query: str - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, - global_string_path: str, - global_string_query: Optional[str] = None, - *, - endpoint: str = "http://localhost:3000", - **kwargs: Any - ) -> None: - self._config = AutoRestUrlTestServiceConfiguration( - global_string_path=global_string_path, global_string_query=global_string_query, **kwargs - ) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `urllowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from urllowlevel.rest import paths - >>> request = paths.build_get_boolean_true_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestUrlTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_configuration.py deleted file mode 100644 index f8cd1ba7b7d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_configuration.py +++ /dev/null @@ -1,52 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestUrlTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestUrlTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param global_string_path: A string value 'globalItemStringPath' that appears in the path. - Required. - :type global_string_path: str - :param global_string_query: should contain value null. Default value is None. - :type global_string_query: str - """ - - def __init__(self, global_string_path: str, global_string_query: Optional[str] = None, **kwargs: Any) -> None: - super(AutoRestUrlTestServiceConfiguration, self).__init__(**kwargs) - if global_string_path is None: - raise ValueError("Parameter 'global_string_path' must not be None.") - - self.global_string_path = global_string_path - self.global_string_query = global_string_query - kwargs.setdefault("sdk_moniker", "autoresturltestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_vendor.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/__init__.py deleted file mode 100644 index fcbb24ae1e7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestUrlTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestUrlTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_client.py deleted file mode 100644 index 2ccb8cc10b9..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_client.py +++ /dev/null @@ -1,85 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, Optional, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestUrlTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestUrlTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :param global_string_path: A string value 'globalItemStringPath' that appears in the path. - Required. - :type global_string_path: str - :param global_string_query: should contain value null. Default value is None. - :type global_string_query: str - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__( - self, - global_string_path: str, - global_string_query: Optional[str] = None, - *, - endpoint: str = "http://localhost:3000", - **kwargs: Any - ) -> None: - self._config = AutoRestUrlTestServiceConfiguration( - global_string_path=global_string_path, global_string_query=global_string_query, **kwargs - ) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `urllowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from urllowlevel.rest import paths - >>> request = paths.build_get_boolean_true_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestUrlTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_configuration.py deleted file mode 100644 index 668c5cc14cc..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_configuration.py +++ /dev/null @@ -1,49 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any, Optional - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestUrlTestServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestUrlTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param global_string_path: A string value 'globalItemStringPath' that appears in the path. - Required. - :type global_string_path: str - :param global_string_query: should contain value null. Default value is None. - :type global_string_query: str - """ - - def __init__(self, global_string_path: str, global_string_query: Optional[str] = None, **kwargs: Any) -> None: - super(AutoRestUrlTestServiceConfiguration, self).__init__(**kwargs) - if global_string_path is None: - raise ValueError("Parameter 'global_string_path' must not be None.") - - self.global_string_path = global_string_path - self.global_string_query = global_string_query - kwargs.setdefault("sdk_moniker", "autoresturltestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/path_items/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/path_items/__init__.py deleted file mode 100644 index 9f90e443bea..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/path_items/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_all_with_values_request -from ._request_builders import build_get_global_query_null_request -from ._request_builders import build_get_global_and_local_query_null_request -from ._request_builders import build_get_local_path_item_query_null_request - -__all__ = [ - "build_get_all_with_values_request", - "build_get_global_query_null_request", - "build_get_global_and_local_query_null_request", - "build_get_local_path_item_query_null_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/path_items/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/path_items/_request_builders.py deleted file mode 100644 index 57d916c5913..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/path_items/_request_builders.py +++ /dev/null @@ -1,284 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_all_with_values_request( - path_item_string_path: str, - local_string_path: str, - global_string_path: str, - *, - path_item_string_query: Optional[str] = None, - local_string_query: Optional[str] = None, - global_string_query: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - """send globalStringPath='globalStringPath', pathItemStringPath='pathItemStringPath', - localStringPath='localStringPath', globalStringQuery='globalStringQuery', - pathItemStringQuery='pathItemStringQuery', localStringQuery='localStringQuery'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param path_item_string_path: A string value 'pathItemStringPath' that appears in the path. - Required. - :type path_item_string_path: str - :param local_string_path: should contain value 'localStringPath'. Required. - :type local_string_path: str - :param global_string_path: A string value 'globalItemStringPath' that appears in the path. - Required. - :type global_string_path: str - :keyword path_item_string_query: A string value 'pathItemStringQuery' that appears as a query - parameter. Default value is None. - :paramtype path_item_string_query: str - :keyword local_string_query: should contain value 'localStringQuery'. Default value is None. - :paramtype local_string_query: str - :keyword global_string_query: should contain value null. Default value is None. - :paramtype global_string_query: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/globalStringQuery/pathItemStringQuery/localStringQuery" # pylint: disable=line-too-long - path_format_arguments = { - "pathItemStringPath": _SERIALIZER.url("path_item_string_path", path_item_string_path, "str"), - "globalStringPath": _SERIALIZER.url("global_string_path", global_string_path, "str"), - "localStringPath": _SERIALIZER.url("local_string_path", local_string_path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - if path_item_string_query is not None: - _params["pathItemStringQuery"] = _SERIALIZER.query("path_item_string_query", path_item_string_query, "str") - if global_string_query is not None: - _params["globalStringQuery"] = _SERIALIZER.query("global_string_query", global_string_query, "str") - if local_string_query is not None: - _params["localStringQuery"] = _SERIALIZER.query("local_string_query", local_string_query, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_global_query_null_request( - path_item_string_path: str, - local_string_path: str, - global_string_path: str, - *, - path_item_string_query: Optional[str] = None, - local_string_query: Optional[str] = None, - global_string_query: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - """send globalStringPath='globalStringPath', pathItemStringPath='pathItemStringPath', - localStringPath='localStringPath', globalStringQuery=null, - pathItemStringQuery='pathItemStringQuery', localStringQuery='localStringQuery'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param path_item_string_path: A string value 'pathItemStringPath' that appears in the path. - Required. - :type path_item_string_path: str - :param local_string_path: should contain value 'localStringPath'. Required. - :type local_string_path: str - :param global_string_path: A string value 'globalItemStringPath' that appears in the path. - Required. - :type global_string_path: str - :keyword path_item_string_query: A string value 'pathItemStringQuery' that appears as a query - parameter. Default value is None. - :paramtype path_item_string_query: str - :keyword local_string_query: should contain value 'localStringQuery'. Default value is None. - :paramtype local_string_query: str - :keyword global_string_query: should contain value null. Default value is None. - :paramtype global_string_query: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/null/pathItemStringQuery/localStringQuery" # pylint: disable=line-too-long - path_format_arguments = { - "pathItemStringPath": _SERIALIZER.url("path_item_string_path", path_item_string_path, "str"), - "globalStringPath": _SERIALIZER.url("global_string_path", global_string_path, "str"), - "localStringPath": _SERIALIZER.url("local_string_path", local_string_path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - if path_item_string_query is not None: - _params["pathItemStringQuery"] = _SERIALIZER.query("path_item_string_query", path_item_string_query, "str") - if global_string_query is not None: - _params["globalStringQuery"] = _SERIALIZER.query("global_string_query", global_string_query, "str") - if local_string_query is not None: - _params["localStringQuery"] = _SERIALIZER.query("local_string_query", local_string_query, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_global_and_local_query_null_request( - path_item_string_path: str, - local_string_path: str, - global_string_path: str, - *, - path_item_string_query: Optional[str] = None, - local_string_query: Optional[str] = None, - global_string_query: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - """send globalStringPath=globalStringPath, pathItemStringPath='pathItemStringPath', - localStringPath='localStringPath', globalStringQuery=null, - pathItemStringQuery='pathItemStringQuery', localStringQuery=null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param path_item_string_path: A string value 'pathItemStringPath' that appears in the path. - Required. - :type path_item_string_path: str - :param local_string_path: should contain value 'localStringPath'. Required. - :type local_string_path: str - :param global_string_path: A string value 'globalItemStringPath' that appears in the path. - Required. - :type global_string_path: str - :keyword path_item_string_query: A string value 'pathItemStringQuery' that appears as a query - parameter. Default value is None. - :paramtype path_item_string_query: str - :keyword local_string_query: should contain null value. Default value is None. - :paramtype local_string_query: str - :keyword global_string_query: should contain value null. Default value is None. - :paramtype global_string_query: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/null/pathItemStringQuery/null" # pylint: disable=line-too-long - path_format_arguments = { - "pathItemStringPath": _SERIALIZER.url("path_item_string_path", path_item_string_path, "str"), - "globalStringPath": _SERIALIZER.url("global_string_path", global_string_path, "str"), - "localStringPath": _SERIALIZER.url("local_string_path", local_string_path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - if path_item_string_query is not None: - _params["pathItemStringQuery"] = _SERIALIZER.query("path_item_string_query", path_item_string_query, "str") - if global_string_query is not None: - _params["globalStringQuery"] = _SERIALIZER.query("global_string_query", global_string_query, "str") - if local_string_query is not None: - _params["localStringQuery"] = _SERIALIZER.query("local_string_query", local_string_query, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_local_path_item_query_null_request( - path_item_string_path: str, - local_string_path: str, - global_string_path: str, - *, - path_item_string_query: Optional[str] = None, - local_string_query: Optional[str] = None, - global_string_query: Optional[str] = None, - **kwargs: Any -) -> HttpRequest: - """send globalStringPath='globalStringPath', pathItemStringPath='pathItemStringPath', - localStringPath='localStringPath', globalStringQuery='globalStringQuery', - pathItemStringQuery=null, localStringQuery=null. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param path_item_string_path: A string value 'pathItemStringPath' that appears in the path. - Required. - :type path_item_string_path: str - :param local_string_path: should contain value 'localStringPath'. Required. - :type local_string_path: str - :param global_string_path: A string value 'globalItemStringPath' that appears in the path. - Required. - :type global_string_path: str - :keyword path_item_string_query: should contain value null. Default value is None. - :paramtype path_item_string_query: str - :keyword local_string_query: should contain value null. Default value is None. - :paramtype local_string_query: str - :keyword global_string_query: should contain value null. Default value is None. - :paramtype global_string_query: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/pathitem/nullable/globalStringPath/{globalStringPath}/pathItemStringPath/{pathItemStringPath}/localStringPath/{localStringPath}/globalStringQuery/null/null" # pylint: disable=line-too-long - path_format_arguments = { - "pathItemStringPath": _SERIALIZER.url("path_item_string_path", path_item_string_path, "str"), - "globalStringPath": _SERIALIZER.url("global_string_path", global_string_path, "str"), - "localStringPath": _SERIALIZER.url("local_string_path", local_string_path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - if path_item_string_query is not None: - _params["pathItemStringQuery"] = _SERIALIZER.query("path_item_string_query", path_item_string_query, "str") - if global_string_query is not None: - _params["globalStringQuery"] = _SERIALIZER.query("global_string_query", global_string_query, "str") - if local_string_query is not None: - _params["localStringQuery"] = _SERIALIZER.query("local_string_query", local_string_query, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/paths/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/paths/__init__.py deleted file mode 100644 index 28cfd1efc0a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/paths/__init__.py +++ /dev/null @@ -1,65 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_boolean_true_request -from ._request_builders import build_get_boolean_false_request -from ._request_builders import build_get_int_one_million_request -from ._request_builders import build_get_int_negative_one_million_request -from ._request_builders import build_get_ten_billion_request -from ._request_builders import build_get_negative_ten_billion_request -from ._request_builders import build_float_scientific_positive_request -from ._request_builders import build_float_scientific_negative_request -from ._request_builders import build_double_decimal_positive_request -from ._request_builders import build_double_decimal_negative_request -from ._request_builders import build_string_unicode_request -from ._request_builders import build_string_url_encoded_request -from ._request_builders import build_string_url_non_encoded_request -from ._request_builders import build_string_empty_request -from ._request_builders import build_string_null_request -from ._request_builders import build_enum_valid_request -from ._request_builders import build_enum_null_request -from ._request_builders import build_byte_multi_byte_request -from ._request_builders import build_byte_empty_request -from ._request_builders import build_byte_null_request -from ._request_builders import build_date_valid_request -from ._request_builders import build_date_null_request -from ._request_builders import build_date_time_valid_request -from ._request_builders import build_date_time_null_request -from ._request_builders import build_base64_url_request -from ._request_builders import build_array_csv_in_path_request -from ._request_builders import build_unix_time_url_request - -__all__ = [ - "build_get_boolean_true_request", - "build_get_boolean_false_request", - "build_get_int_one_million_request", - "build_get_int_negative_one_million_request", - "build_get_ten_billion_request", - "build_get_negative_ten_billion_request", - "build_float_scientific_positive_request", - "build_float_scientific_negative_request", - "build_double_decimal_positive_request", - "build_double_decimal_negative_request", - "build_string_unicode_request", - "build_string_url_encoded_request", - "build_string_url_non_encoded_request", - "build_string_empty_request", - "build_string_null_request", - "build_enum_valid_request", - "build_enum_null_request", - "build_byte_multi_byte_request", - "build_byte_empty_request", - "build_byte_null_request", - "build_date_valid_request", - "build_date_null_request", - "build_date_time_valid_request", - "build_date_time_null_request", - "build_base64_url_request", - "build_array_csv_in_path_request", - "build_unix_time_url_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/paths/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/paths/_request_builders.py deleted file mode 100644 index 68f1a61294b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/paths/_request_builders.py +++ /dev/null @@ -1,928 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -from typing import Any, List - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_boolean_true_request(**kwargs: Any) -> HttpRequest: - """Get true Boolean value on path. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword bool_path: true boolean value. Default value is True. Note that overriding this - default value may result in unsupported behavior. - :paramtype bool_path: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - bool_path = kwargs.pop("bool_path", True) # type: bool - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/bool/true/{boolPath}" - path_format_arguments = { - "boolPath": _SERIALIZER.url("bool_path", bool_path, "bool"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_boolean_false_request(**kwargs: Any) -> HttpRequest: - """Get false Boolean value on path. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword bool_path: false boolean value. Required. Default value is False. Note that overriding - this default value may result in unsupported behavior. - :paramtype bool_path: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - bool_path = kwargs.pop("bool_path", False) # type: bool - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/bool/false/{boolPath}" - path_format_arguments = { - "boolPath": _SERIALIZER.url("bool_path", bool_path, "bool"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_int_one_million_request(**kwargs: Any) -> HttpRequest: - """Get '1000000' integer value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword int_path: '1000000' integer value. Default value is 1000000. Note that overriding this - default value may result in unsupported behavior. - :paramtype int_path: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - int_path = kwargs.pop("int_path", 1000000) # type: int - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/int/1000000/{intPath}" - path_format_arguments = { - "intPath": _SERIALIZER.url("int_path", int_path, "int"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_int_negative_one_million_request(**kwargs: Any) -> HttpRequest: - """Get '-1000000' integer value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword int_path: '-1000000' integer value. Default value is -1000000. Note that overriding - this default value may result in unsupported behavior. - :paramtype int_path: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - int_path = kwargs.pop("int_path", -1000000) # type: int - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/int/-1000000/{intPath}" - path_format_arguments = { - "intPath": _SERIALIZER.url("int_path", int_path, "int"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_ten_billion_request(**kwargs: Any) -> HttpRequest: - """Get '10000000000' 64 bit integer value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword long_path: '10000000000' 64 bit integer value. Default value is 10000000000. Note that - overriding this default value may result in unsupported behavior. - :paramtype long_path: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - long_path = kwargs.pop("long_path", 10000000000) # type: int - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/long/10000000000/{longPath}" - path_format_arguments = { - "longPath": _SERIALIZER.url("long_path", long_path, "int"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_negative_ten_billion_request(**kwargs: Any) -> HttpRequest: - """Get '-10000000000' 64 bit integer value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword long_path: '-10000000000' 64 bit integer value. Default value is -10000000000. Note - that overriding this default value may result in unsupported behavior. - :paramtype long_path: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - long_path = kwargs.pop("long_path", -10000000000) # type: int - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/long/-10000000000/{longPath}" - path_format_arguments = { - "longPath": _SERIALIZER.url("long_path", long_path, "int"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_float_scientific_positive_request(**kwargs: Any) -> HttpRequest: - """Get '1.034E+20' numeric value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword float_path: '1.034E+20'numeric value. Default value is 103400000000000000000. Note - that overriding this default value may result in unsupported behavior. - :paramtype float_path: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - float_path = kwargs.pop("float_path", 103400000000000000000) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/float/1.034E+20/{floatPath}" - path_format_arguments = { - "floatPath": _SERIALIZER.url("float_path", float_path, "float"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_float_scientific_negative_request(**kwargs: Any) -> HttpRequest: - """Get '-1.034E-20' numeric value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword float_path: '-1.034E-20'numeric value. Default value is -1.034e-20. Note that - overriding this default value may result in unsupported behavior. - :paramtype float_path: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - float_path = kwargs.pop("float_path", -1.034e-20) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/float/-1.034E-20/{floatPath}" - path_format_arguments = { - "floatPath": _SERIALIZER.url("float_path", float_path, "float"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_double_decimal_positive_request(**kwargs: Any) -> HttpRequest: - """Get '9999999.999' numeric value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword double_path: '9999999.999'numeric value. Default value is 9999999.999. Note that - overriding this default value may result in unsupported behavior. - :paramtype double_path: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - double_path = kwargs.pop("double_path", 9999999.999) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/double/9999999.999/{doublePath}" - path_format_arguments = { - "doublePath": _SERIALIZER.url("double_path", double_path, "float"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_double_decimal_negative_request(**kwargs: Any) -> HttpRequest: - """Get '-9999999.999' numeric value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword double_path: '-9999999.999'numeric value. Default value is -9999999.999. Note that - overriding this default value may result in unsupported behavior. - :paramtype double_path: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - double_path = kwargs.pop("double_path", -9999999.999) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/double/-9999999.999/{doublePath}" - path_format_arguments = { - "doublePath": _SERIALIZER.url("double_path", double_path, "float"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_string_unicode_request(**kwargs: Any) -> HttpRequest: - """Get '啊齄丂狛狜隣郎隣兀﨩' multi-byte string value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword string_path: '啊齄丂狛狜隣郎隣兀﨩'multi-byte string value. Default value is "啊齄丂狛狜隣郎隣兀﨩". Note - that overriding this default value may result in unsupported behavior. - :paramtype string_path: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - string_path = kwargs.pop("string_path", "啊齄丂狛狜隣郎隣兀﨩") # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/string/unicode/{stringPath}" - path_format_arguments = { - "stringPath": _SERIALIZER.url("string_path", string_path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_string_url_encoded_request(**kwargs: Any) -> HttpRequest: - """Get 'begin!*'();:@ &=+$,/?#[]end. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword string_path: 'begin!*'();:@ &=+$,/?#[]end' url encoded string value. Default value is - "begin!*'();:@ &=+$,/?#[]end". Note that overriding this default value may result in - unsupported behavior. - :paramtype string_path: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - string_path = kwargs.pop("string_path", "begin!*'();:@ &=+$,/?#[]end") # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/string/begin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend/{stringPath}" - path_format_arguments = { - "stringPath": _SERIALIZER.url("string_path", string_path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_string_url_non_encoded_request(**kwargs: Any) -> HttpRequest: - """Get 'begin!*'();:@&=+$,end. - - https://tools.ietf.org/html/rfc3986#appendix-A 'path' accept any 'pchar' not encoded. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword string_path: 'begin!*'();:@&=+$,end' url encoded string value. Default value is - "begin!*'();:@&=+$,end". Note that overriding this default value may result in unsupported - behavior. - :paramtype string_path: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - string_path = kwargs.pop("string_path", "begin!*'();:@&=+$,end") # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/string/begin!*'();:@&=+$,end/{stringPath}" - path_format_arguments = { - "stringPath": _SERIALIZER.url("string_path", string_path, "str", skip_quote=True), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_string_empty_request(**kwargs: Any) -> HttpRequest: - """Get ''. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword string_path: '' string value. Required. Default value is "". Note that overriding this - default value may result in unsupported behavior. - :paramtype string_path: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - string_path = kwargs.pop("string_path", "") # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/string/empty/{stringPath}" - path_format_arguments = { - "stringPath": _SERIALIZER.url("string_path", string_path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_string_null_request(string_path: str, **kwargs: Any) -> HttpRequest: - """Get null (should throw). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param string_path: null string value. Required. - :type string_path: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/string/null/{stringPath}" - path_format_arguments = { - "stringPath": _SERIALIZER.url("string_path", string_path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_enum_valid_request(enum_path: str, **kwargs: Any) -> HttpRequest: - """Get using uri with 'green color' in path parameter. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param enum_path: send the value green. Known values are: "red color", "green color", and "blue - color". Required. - :type enum_path: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/enum/green%20color/{enumPath}" - path_format_arguments = { - "enumPath": _SERIALIZER.url("enum_path", enum_path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_enum_null_request(enum_path: str, **kwargs: Any) -> HttpRequest: - """Get null (should throw on the client before the request is sent on wire). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param enum_path: send null should throw. Known values are: "red color", "green color", and - "blue color". Required. - :type enum_path: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/string/null/{enumPath}" - path_format_arguments = { - "enumPath": _SERIALIZER.url("enum_path", enum_path, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_byte_multi_byte_request(byte_path: bytes, **kwargs: Any) -> HttpRequest: - """Get '啊齄丂狛狜隣郎隣兀﨩' multibyte value as utf-8 encoded byte array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param byte_path: '啊齄丂狛狜隣郎隣兀﨩' multibyte value as utf-8 encoded byte array. Required. - :type byte_path: bytes - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/byte/multibyte/{bytePath}" - path_format_arguments = { - "bytePath": _SERIALIZER.url("byte_path", byte_path, "bytearray"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_byte_empty_request(**kwargs: Any) -> HttpRequest: - """Get '' as byte array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword byte_path: '' as byte array. Required. Default value is bytes("", encoding="utf-8"). - Note that overriding this default value may result in unsupported behavior. - :paramtype byte_path: bytes - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - byte_path = kwargs.pop("byte_path", bytes("", encoding="utf-8")) # type: bytes - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/byte/empty/{bytePath}" - path_format_arguments = { - "bytePath": _SERIALIZER.url("byte_path", byte_path, "bytearray"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_byte_null_request(byte_path: bytes, **kwargs: Any) -> HttpRequest: - """Get null as byte array (should throw). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param byte_path: null as byte array (should throw). Required. - :type byte_path: bytes - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/byte/null/{bytePath}" - path_format_arguments = { - "bytePath": _SERIALIZER.url("byte_path", byte_path, "bytearray"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_date_valid_request(**kwargs: Any) -> HttpRequest: - """Get '2012-01-01' as date. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword date_path: '2012-01-01' as date. Default value is "2012-01-01". Note that overriding - this default value may result in unsupported behavior. - :paramtype date_path: ~datetime.date - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - date_path = kwargs.pop("date_path", "2012-01-01") # type: datetime.date - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/date/2012-01-01/{datePath}" - path_format_arguments = { - "datePath": _SERIALIZER.url("date_path", date_path, "date"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_date_null_request(date_path: datetime.date, **kwargs: Any) -> HttpRequest: - """Get null as date - this should throw or be unusable on the client side, depending on date - representation. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param date_path: null as date (should throw). Required. - :type date_path: ~datetime.date - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/date/null/{datePath}" - path_format_arguments = { - "datePath": _SERIALIZER.url("date_path", date_path, "date"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_date_time_valid_request(**kwargs: Any) -> HttpRequest: - """Get '2012-01-01T01:01:01Z' as date-time. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword date_time_path: '2012-01-01T01:01:01Z' as date-time. Default value is - "2012-01-01T01:01:01Z". Note that overriding this default value may result in unsupported - behavior. - :paramtype date_time_path: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - date_time_path = kwargs.pop("date_time_path", "2012-01-01T01:01:01Z") # type: datetime.datetime - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/datetime/2012-01-01T01%3A01%3A01Z/{dateTimePath}" - path_format_arguments = { - "dateTimePath": _SERIALIZER.url("date_time_path", date_time_path, "iso-8601"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_date_time_null_request(date_time_path: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Get null as date-time, should be disallowed or throw depending on representation of date-time. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param date_time_path: null as date-time. Required. - :type date_time_path: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/datetime/null/{dateTimePath}" - path_format_arguments = { - "dateTimePath": _SERIALIZER.url("date_time_path", date_time_path, "iso-8601"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_base64_url_request(base64_url_path: bytes, **kwargs: Any) -> HttpRequest: - """Get 'lorem' encoded value as 'bG9yZW0' (base64url). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param base64_url_path: base64url encoded value. Required. - :type base64_url_path: bytes - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/string/bG9yZW0/{base64UrlPath}" - path_format_arguments = { - "base64UrlPath": _SERIALIZER.url("base64_url_path", base64_url_path, "base64"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_array_csv_in_path_request(array_path: List[str], **kwargs: Any) -> HttpRequest: - """Get an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the - csv-array format. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param array_path: an array of string ['ArrayPath1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] - using the csv-array format. Required. - :type array_path: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = ( - "/paths/array/ArrayPath1%2cbegin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend%2c%2c/{arrayPath}" - ) - path_format_arguments = { - "arrayPath": _SERIALIZER.url("array_path", array_path, "[str]", div=","), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_unix_time_url_request(unix_time_url_path: datetime.datetime, **kwargs: Any) -> HttpRequest: - """Get the date 2016-04-13 encoded value as '1460505600' (Unix time). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param unix_time_url_path: Unix time encoded value. Required. - :type unix_time_url_path: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/paths/int/1460505600/{unixTimeUrlPath}" - path_format_arguments = { - "unixTimeUrlPath": _SERIALIZER.url("unix_time_url_path", unix_time_url_path, "unix-time"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/queries/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/queries/__init__.py deleted file mode 100644 index b12dab2a4ae..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/queries/__init__.py +++ /dev/null @@ -1,81 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_boolean_true_request -from ._request_builders import build_get_boolean_false_request -from ._request_builders import build_get_boolean_null_request -from ._request_builders import build_get_int_one_million_request -from ._request_builders import build_get_int_negative_one_million_request -from ._request_builders import build_get_int_null_request -from ._request_builders import build_get_ten_billion_request -from ._request_builders import build_get_negative_ten_billion_request -from ._request_builders import build_get_long_null_request -from ._request_builders import build_float_scientific_positive_request -from ._request_builders import build_float_scientific_negative_request -from ._request_builders import build_float_null_request -from ._request_builders import build_double_decimal_positive_request -from ._request_builders import build_double_decimal_negative_request -from ._request_builders import build_double_null_request -from ._request_builders import build_string_unicode_request -from ._request_builders import build_string_url_encoded_request -from ._request_builders import build_string_empty_request -from ._request_builders import build_string_null_request -from ._request_builders import build_enum_valid_request -from ._request_builders import build_enum_null_request -from ._request_builders import build_byte_multi_byte_request -from ._request_builders import build_byte_empty_request -from ._request_builders import build_byte_null_request -from ._request_builders import build_date_valid_request -from ._request_builders import build_date_null_request -from ._request_builders import build_date_time_valid_request -from ._request_builders import build_date_time_null_request -from ._request_builders import build_array_string_csv_valid_request -from ._request_builders import build_array_string_csv_null_request -from ._request_builders import build_array_string_csv_empty_request -from ._request_builders import build_array_string_no_collection_format_empty_request -from ._request_builders import build_array_string_ssv_valid_request -from ._request_builders import build_array_string_tsv_valid_request -from ._request_builders import build_array_string_pipes_valid_request - -__all__ = [ - "build_get_boolean_true_request", - "build_get_boolean_false_request", - "build_get_boolean_null_request", - "build_get_int_one_million_request", - "build_get_int_negative_one_million_request", - "build_get_int_null_request", - "build_get_ten_billion_request", - "build_get_negative_ten_billion_request", - "build_get_long_null_request", - "build_float_scientific_positive_request", - "build_float_scientific_negative_request", - "build_float_null_request", - "build_double_decimal_positive_request", - "build_double_decimal_negative_request", - "build_double_null_request", - "build_string_unicode_request", - "build_string_url_encoded_request", - "build_string_empty_request", - "build_string_null_request", - "build_enum_valid_request", - "build_enum_null_request", - "build_byte_multi_byte_request", - "build_byte_empty_request", - "build_byte_null_request", - "build_date_valid_request", - "build_date_null_request", - "build_date_time_valid_request", - "build_date_time_null_request", - "build_array_string_csv_valid_request", - "build_array_string_csv_null_request", - "build_array_string_csv_empty_request", - "build_array_string_no_collection_format_empty_request", - "build_array_string_ssv_valid_request", - "build_array_string_tsv_valid_request", - "build_array_string_pipes_valid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/queries/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/queries/_request_builders.py deleted file mode 100644 index aa74628d822..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlLowLevel/urllowlevel/rest/queries/_request_builders.py +++ /dev/null @@ -1,1173 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import datetime -from typing import Any, List, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_boolean_true_request(**kwargs: Any) -> HttpRequest: - """Get true Boolean value on path. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword bool_query: true boolean value. Default value is True. Note that overriding this - default value may result in unsupported behavior. - :paramtype bool_query: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - bool_query = kwargs.pop("bool_query", _params.pop("boolQuery", True)) # type: bool - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/bool/true" - - # Construct parameters - _params["boolQuery"] = _SERIALIZER.query("bool_query", bool_query, "bool") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_boolean_false_request(**kwargs: Any) -> HttpRequest: - """Get false Boolean value on path. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword bool_query: false boolean value. Required. Default value is False. Note that - overriding this default value may result in unsupported behavior. - :paramtype bool_query: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - bool_query = kwargs.pop("bool_query", _params.pop("boolQuery", False)) # type: bool - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/bool/false" - - # Construct parameters - _params["boolQuery"] = _SERIALIZER.query("bool_query", bool_query, "bool") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_boolean_null_request(*, bool_query: Optional[bool] = None, **kwargs: Any) -> HttpRequest: - """Get null Boolean value on query (query string should be absent). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword bool_query: null boolean value. Default value is None. - :paramtype bool_query: bool - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/bool/null" - - # Construct parameters - if bool_query is not None: - _params["boolQuery"] = _SERIALIZER.query("bool_query", bool_query, "bool") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_int_one_million_request(**kwargs: Any) -> HttpRequest: - """Get '1000000' integer value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword int_query: '1000000' integer value. Default value is 1000000. Note that overriding - this default value may result in unsupported behavior. - :paramtype int_query: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - int_query = kwargs.pop("int_query", _params.pop("intQuery", 1000000)) # type: int - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/int/1000000" - - # Construct parameters - _params["intQuery"] = _SERIALIZER.query("int_query", int_query, "int") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_int_negative_one_million_request(**kwargs: Any) -> HttpRequest: - """Get '-1000000' integer value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword int_query: '-1000000' integer value. Default value is -1000000. Note that overriding - this default value may result in unsupported behavior. - :paramtype int_query: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - int_query = kwargs.pop("int_query", _params.pop("intQuery", -1000000)) # type: int - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/int/-1000000" - - # Construct parameters - _params["intQuery"] = _SERIALIZER.query("int_query", int_query, "int") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_int_null_request(*, int_query: Optional[int] = None, **kwargs: Any) -> HttpRequest: - """Get null integer value (no query parameter). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword int_query: null integer value. Default value is None. - :paramtype int_query: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/int/null" - - # Construct parameters - if int_query is not None: - _params["intQuery"] = _SERIALIZER.query("int_query", int_query, "int") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_ten_billion_request(**kwargs: Any) -> HttpRequest: - """Get '10000000000' 64 bit integer value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword long_query: '10000000000' 64 bit integer value. Default value is 10000000000. Note - that overriding this default value may result in unsupported behavior. - :paramtype long_query: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - long_query = kwargs.pop("long_query", _params.pop("longQuery", 10000000000)) # type: int - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/long/10000000000" - - # Construct parameters - _params["longQuery"] = _SERIALIZER.query("long_query", long_query, "int") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_negative_ten_billion_request(**kwargs: Any) -> HttpRequest: - """Get '-10000000000' 64 bit integer value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword long_query: '-10000000000' 64 bit integer value. Default value is -10000000000. Note - that overriding this default value may result in unsupported behavior. - :paramtype long_query: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - long_query = kwargs.pop("long_query", _params.pop("longQuery", -10000000000)) # type: int - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/long/-10000000000" - - # Construct parameters - _params["longQuery"] = _SERIALIZER.query("long_query", long_query, "int") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_long_null_request(*, long_query: Optional[int] = None, **kwargs: Any) -> HttpRequest: - """Get 'null 64 bit integer value (no query param in uri). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword long_query: null 64 bit integer value. Default value is None. - :paramtype long_query: int - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/long/null" - - # Construct parameters - if long_query is not None: - _params["longQuery"] = _SERIALIZER.query("long_query", long_query, "int") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_float_scientific_positive_request(**kwargs: Any) -> HttpRequest: - """Get '1.034E+20' numeric value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword float_query: '1.034E+20'numeric value. Default value is 103400000000000000000. Note - that overriding this default value may result in unsupported behavior. - :paramtype float_query: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - float_query = kwargs.pop("float_query", _params.pop("floatQuery", 103400000000000000000)) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/float/1.034E+20" - - # Construct parameters - _params["floatQuery"] = _SERIALIZER.query("float_query", float_query, "float") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_float_scientific_negative_request(**kwargs: Any) -> HttpRequest: - """Get '-1.034E-20' numeric value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword float_query: '-1.034E-20'numeric value. Default value is -1.034e-20. Note that - overriding this default value may result in unsupported behavior. - :paramtype float_query: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - float_query = kwargs.pop("float_query", _params.pop("floatQuery", -1.034e-20)) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/float/-1.034E-20" - - # Construct parameters - _params["floatQuery"] = _SERIALIZER.query("float_query", float_query, "float") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_float_null_request(*, float_query: Optional[float] = None, **kwargs: Any) -> HttpRequest: - """Get null numeric value (no query parameter). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword float_query: null numeric value. Default value is None. - :paramtype float_query: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/float/null" - - # Construct parameters - if float_query is not None: - _params["floatQuery"] = _SERIALIZER.query("float_query", float_query, "float") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_double_decimal_positive_request(**kwargs: Any) -> HttpRequest: - """Get '9999999.999' numeric value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword double_query: '9999999.999'numeric value. Default value is 9999999.999. Note that - overriding this default value may result in unsupported behavior. - :paramtype double_query: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - double_query = kwargs.pop("double_query", _params.pop("doubleQuery", 9999999.999)) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/double/9999999.999" - - # Construct parameters - _params["doubleQuery"] = _SERIALIZER.query("double_query", double_query, "float") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_double_decimal_negative_request(**kwargs: Any) -> HttpRequest: - """Get '-9999999.999' numeric value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword double_query: '-9999999.999'numeric value. Default value is -9999999.999. Note that - overriding this default value may result in unsupported behavior. - :paramtype double_query: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - double_query = kwargs.pop("double_query", _params.pop("doubleQuery", -9999999.999)) # type: float - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/double/-9999999.999" - - # Construct parameters - _params["doubleQuery"] = _SERIALIZER.query("double_query", double_query, "float") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_double_null_request(*, double_query: Optional[float] = None, **kwargs: Any) -> HttpRequest: - """Get null numeric value (no query parameter). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword double_query: null numeric value. Default value is None. - :paramtype double_query: float - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/double/null" - - # Construct parameters - if double_query is not None: - _params["doubleQuery"] = _SERIALIZER.query("double_query", double_query, "float") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_string_unicode_request(**kwargs: Any) -> HttpRequest: - """Get '啊齄丂狛狜隣郎隣兀﨩' multi-byte string value. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword string_query: '啊齄丂狛狜隣郎隣兀﨩'multi-byte string value. Default value is "啊齄丂狛狜隣郎隣兀﨩". Note - that overriding this default value may result in unsupported behavior. - :paramtype string_query: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - string_query = kwargs.pop("string_query", _params.pop("stringQuery", "啊齄丂狛狜隣郎隣兀﨩")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/string/unicode/" - - # Construct parameters - _params["stringQuery"] = _SERIALIZER.query("string_query", string_query, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_string_url_encoded_request(**kwargs: Any) -> HttpRequest: - """Get 'begin!*'();:@ &=+$,/?#[]end. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword string_query: 'begin!*'();:@ &=+$,/?#[]end' url encoded string value. Default value is - "begin!*'();:@ &=+$,/?#[]end". Note that overriding this default value may result in - unsupported behavior. - :paramtype string_query: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - string_query = kwargs.pop("string_query", _params.pop("stringQuery", "begin!*'();:@ &=+$,/?#[]end")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/string/begin%21%2A%27%28%29%3B%3A%40%20%26%3D%2B%24%2C%2F%3F%23%5B%5Dend" - - # Construct parameters - _params["stringQuery"] = _SERIALIZER.query("string_query", string_query, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_string_empty_request(**kwargs: Any) -> HttpRequest: - """Get ''. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword string_query: '' string value. Required. Default value is "". Note that overriding - this default value may result in unsupported behavior. - :paramtype string_query: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - string_query = kwargs.pop("string_query", _params.pop("stringQuery", "")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/string/empty" - - # Construct parameters - _params["stringQuery"] = _SERIALIZER.query("string_query", string_query, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_string_null_request(*, string_query: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Get null (no query parameter in url). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword string_query: null string value. Default value is None. - :paramtype string_query: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/string/null" - - # Construct parameters - if string_query is not None: - _params["stringQuery"] = _SERIALIZER.query("string_query", string_query, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_enum_valid_request(*, enum_query: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Get using uri with query parameter 'green color'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword enum_query: 'green color' enum value. Known values are: "red color", "green color", - and "blue color". Default value is None. - :paramtype enum_query: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/enum/green%20color" - - # Construct parameters - if enum_query is not None: - _params["enumQuery"] = _SERIALIZER.query("enum_query", enum_query, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_enum_null_request(*, enum_query: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """Get null (no query parameter in url). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword enum_query: null string value. Known values are: "red color", "green color", and "blue - color". Default value is None. - :paramtype enum_query: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/enum/null" - - # Construct parameters - if enum_query is not None: - _params["enumQuery"] = _SERIALIZER.query("enum_query", enum_query, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_byte_multi_byte_request(*, byte_query: Optional[bytes] = None, **kwargs: Any) -> HttpRequest: - """Get '啊齄丂狛狜隣郎隣兀﨩' multibyte value as utf-8 encoded byte array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword byte_query: '啊齄丂狛狜隣郎隣兀﨩' multibyte value as utf-8 encoded byte array. Default value is - None. - :paramtype byte_query: bytes - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/byte/multibyte" - - # Construct parameters - if byte_query is not None: - _params["byteQuery"] = _SERIALIZER.query("byte_query", byte_query, "bytearray") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_byte_empty_request(**kwargs: Any) -> HttpRequest: - """Get '' as byte array. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword byte_query: '' as byte array. Required. Default value is bytes("", encoding="utf-8"). - Note that overriding this default value may result in unsupported behavior. - :paramtype byte_query: bytes - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - byte_query = kwargs.pop("byte_query", _params.pop("byteQuery", bytes("", encoding="utf-8"))) # type: bytes - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/byte/empty" - - # Construct parameters - _params["byteQuery"] = _SERIALIZER.query("byte_query", byte_query, "bytearray") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_byte_null_request(*, byte_query: Optional[bytes] = None, **kwargs: Any) -> HttpRequest: - """Get null as byte array (no query parameters in uri). - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword byte_query: null as byte array (no query parameters in uri). Default value is None. - :paramtype byte_query: bytes - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/byte/null" - - # Construct parameters - if byte_query is not None: - _params["byteQuery"] = _SERIALIZER.query("byte_query", byte_query, "bytearray") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_date_valid_request(**kwargs: Any) -> HttpRequest: - """Get '2012-01-01' as date. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword date_query: '2012-01-01' as date. Default value is "2012-01-01". Note that overriding - this default value may result in unsupported behavior. - :paramtype date_query: ~datetime.date - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - date_query = kwargs.pop("date_query", _params.pop("dateQuery", "2012-01-01")) # type: datetime.date - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/date/2012-01-01" - - # Construct parameters - _params["dateQuery"] = _SERIALIZER.query("date_query", date_query, "date") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_date_null_request(*, date_query: Optional[datetime.date] = None, **kwargs: Any) -> HttpRequest: - """Get null as date - this should result in no query parameters in uri. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword date_query: null as date (no query parameters in uri). Default value is None. - :paramtype date_query: ~datetime.date - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/date/null" - - # Construct parameters - if date_query is not None: - _params["dateQuery"] = _SERIALIZER.query("date_query", date_query, "date") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_date_time_valid_request(**kwargs: Any) -> HttpRequest: - """Get '2012-01-01T01:01:01Z' as date-time. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword date_time_query: '2012-01-01T01:01:01Z' as date-time. Default value is - "2012-01-01T01:01:01Z". Note that overriding this default value may result in unsupported - behavior. - :paramtype date_time_query: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - date_time_query = kwargs.pop( - "date_time_query", _params.pop("dateTimeQuery", "2012-01-01T01:01:01Z") - ) # type: datetime.datetime - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/datetime/2012-01-01T01%3A01%3A01Z" - - # Construct parameters - _params["dateTimeQuery"] = _SERIALIZER.query("date_time_query", date_time_query, "iso-8601") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_date_time_null_request(*, date_time_query: Optional[datetime.datetime] = None, **kwargs: Any) -> HttpRequest: - """Get null as date-time, should result in no query parameters in uri. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword date_time_query: null as date-time (no query parameters). Default value is None. - :paramtype date_time_query: ~datetime.datetime - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/datetime/null" - - # Construct parameters - if date_time_query is not None: - _params["dateTimeQuery"] = _SERIALIZER.query("date_time_query", date_time_query, "iso-8601") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_array_string_csv_valid_request(*, array_query: Optional[List[str]] = None, **kwargs: Any) -> HttpRequest: - """Get an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the - csv-array format. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword array_query: an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, - ''] using the csv-array format. Default value is None. - :paramtype array_query: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/array/csv/string/valid" - - # Construct parameters - if array_query is not None: - _params["arrayQuery"] = _SERIALIZER.query("array_query", array_query, "[str]", div=",") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_array_string_csv_null_request(*, array_query: Optional[List[str]] = None, **kwargs: Any) -> HttpRequest: - """Get a null array of string using the csv-array format. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword array_query: a null array of string using the csv-array format. Default value is None. - :paramtype array_query: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/array/csv/string/null" - - # Construct parameters - if array_query is not None: - _params["arrayQuery"] = _SERIALIZER.query("array_query", array_query, "[str]", div=",") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_array_string_csv_empty_request(*, array_query: Optional[List[str]] = None, **kwargs: Any) -> HttpRequest: - """Get an empty array [] of string using the csv-array format. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword array_query: an empty array [] of string using the csv-array format. Default value is - None. - :paramtype array_query: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/array/csv/string/empty" - - # Construct parameters - if array_query is not None: - _params["arrayQuery"] = _SERIALIZER.query("array_query", array_query, "[str]", div=",") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_array_string_no_collection_format_empty_request( - *, array_query: Optional[List[str]] = None, **kwargs: Any -) -> HttpRequest: - """Array query has no defined collection format, should default to csv. Pass in ['hello', 'nihao', - 'bonjour'] for the 'arrayQuery' parameter to the service. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword array_query: Array-typed query parameter. Pass in ['hello', 'nihao', 'bonjour']. - Default value is None. - :paramtype array_query: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/array/none/string/empty" - - # Construct parameters - if array_query is not None: - _params["arrayQuery"] = _SERIALIZER.query("array_query", array_query, "[str]", div=",") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_array_string_ssv_valid_request(*, array_query: Optional[List[str]] = None, **kwargs: Any) -> HttpRequest: - """Get an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the - ssv-array format. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword array_query: an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, - ''] using the ssv-array format. Default value is None. - :paramtype array_query: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/array/ssv/string/valid" - - # Construct parameters - if array_query is not None: - _params["arrayQuery"] = _SERIALIZER.query("array_query", array_query, "[str]", div=" ") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_array_string_tsv_valid_request(*, array_query: Optional[List[str]] = None, **kwargs: Any) -> HttpRequest: - """Get an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the - tsv-array format. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword array_query: an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, - ''] using the tsv-array format. Default value is None. - :paramtype array_query: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/array/tsv/string/valid" - - # Construct parameters - if array_query is not None: - _params["arrayQuery"] = _SERIALIZER.query("array_query", array_query, "[str]", div=" ") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_array_string_pipes_valid_request(*, array_query: Optional[List[str]] = None, **kwargs: Any) -> HttpRequest: - """Get an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the - pipes-array format. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword array_query: an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, - ''] using the pipes-array format. Default value is None. - :paramtype array_query: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/array/pipes/string/valid" - - # Construct parameters - if array_query is not None: - _params["arrayQuery"] = _SERIALIZER.query("array_query", array_query, "[str]", div="|") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/setup.py deleted file mode 100644 index 91d52a92052..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autoresturlmutlicollectionformattestservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestUrlMutliCollectionFormatTestService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/__init__.py deleted file mode 100644 index 7383f959ddf..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestUrlMutliCollectionFormatTestService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestUrlMutliCollectionFormatTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_client.py deleted file mode 100644 index c2795fafff3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestUrlMutliCollectionFormatTestServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestUrlMutliCollectionFormatTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestUrlMutliCollectionFormatTestServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `urlmulticollectionformatlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from urlmulticollectionformatlowlevel.rest import queries - >>> request = queries.build_array_string_multi_null_request(array_query=array_query, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestUrlMutliCollectionFormatTestService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_configuration.py deleted file mode 100644 index 651fc8e1c1a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_configuration.py +++ /dev/null @@ -1,44 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestUrlMutliCollectionFormatTestServiceConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestUrlMutliCollectionFormatTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestUrlMutliCollectionFormatTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autoresturlmutlicollectionformattestservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/__init__.py deleted file mode 100644 index 3b964630a18..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestUrlMutliCollectionFormatTestService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestUrlMutliCollectionFormatTestService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_client.py deleted file mode 100644 index 9d597ad0e16..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestUrlMutliCollectionFormatTestServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestUrlMutliCollectionFormatTestService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestUrlMutliCollectionFormatTestServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `urlmulticollectionformatlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from urlmulticollectionformatlowlevel.rest import queries - >>> request = queries.build_array_string_multi_null_request(array_query=array_query, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestUrlMutliCollectionFormatTestService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_configuration.py deleted file mode 100644 index 51186d27106..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_configuration.py +++ /dev/null @@ -1,41 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestUrlMutliCollectionFormatTestServiceConfiguration( - Configuration -): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestUrlMutliCollectionFormatTestService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestUrlMutliCollectionFormatTestServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autoresturlmutlicollectionformattestservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/queries/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/queries/__init__.py deleted file mode 100644 index eb552e0489b..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/queries/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_array_string_multi_null_request -from ._request_builders import build_array_string_multi_empty_request -from ._request_builders import build_array_string_multi_valid_request - -__all__ = [ - "build_array_string_multi_null_request", - "build_array_string_multi_empty_request", - "build_array_string_multi_valid_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/queries/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/queries/_request_builders.py deleted file mode 100644 index 0aa3fe805f3..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel/urlmulticollectionformatlowlevel/rest/queries/_request_builders.py +++ /dev/null @@ -1,122 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any, List, Optional - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_array_string_multi_null_request(*, array_query: Optional[List[str]] = None, **kwargs: Any) -> HttpRequest: - """Get a null array of string using the multi-array format. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword array_query: a null array of string using the multi-array format. Default value is - None. - :paramtype array_query: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/array/multi/string/null" - - # Construct parameters - if array_query is not None: - _params["arrayQuery"] = [ - _SERIALIZER.query("array_query", q, "str") if q is not None else "" for q in array_query - ] - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_array_string_multi_empty_request(*, array_query: Optional[List[str]] = None, **kwargs: Any) -> HttpRequest: - """Get an empty array [] of string using the multi-array format. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword array_query: an empty array [] of string using the multi-array format. Default value - is None. - :paramtype array_query: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/array/multi/string/empty" - - # Construct parameters - if array_query is not None: - _params["arrayQuery"] = [ - _SERIALIZER.query("array_query", q, "str") if q is not None else "" for q in array_query - ] - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_array_string_multi_valid_request(*, array_query: Optional[List[str]] = None, **kwargs: Any) -> HttpRequest: - """Get an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, ''] using the - mult-array format. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword array_query: an array of string ['ArrayQuery1', 'begin!*'();:@ &=+$,/?#[]end' , null, - ''] using the mult-array format. Default value is None. - :paramtype array_query: list[str] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/queries/array/multi/string/valid" - - # Construct parameters - if array_query is not None: - _params["arrayQuery"] = [ - _SERIALIZER.query("array_query", q, "str") if q is not None else "" for q in array_query - ] - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/setup.py deleted file mode 100644 index cbbe264d20d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestvalidationtest" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestValidationTest", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest. No server backend exists for these tests. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/__init__.py deleted file mode 100644 index 8e38762b0d7..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestValidationTest -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestValidationTest"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_client.py deleted file mode 100644 index e8d76a38943..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_client.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestValidationTestConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestValidationTest: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. No server backend exists for these tests. - - :param subscription_id: Subscription ID. Required. - :type subscription_id: str - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - :keyword api_version: Api Version. Default value is "1.0.0". Note that overriding this default - value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, subscription_id: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestValidationTestConfiguration(subscription_id=subscription_id, **kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `validationlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from validationlowlevel.rest import build_validation_of_method_parameters_request - >>> request = build_validation_of_method_parameters_request(resource_group_name, id, subscription_id, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestValidationTest - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_configuration.py deleted file mode 100644 index 3c7d59e312d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_configuration.py +++ /dev/null @@ -1,54 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestValidationTestConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestValidationTest. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param subscription_id: Subscription ID. Required. - :type subscription_id: str - :keyword api_version: Api Version. Default value is "1.0.0". Note that overriding this default - value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, subscription_id: str, **kwargs: Any) -> None: - super(AutoRestValidationTestConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "1.0.0") # type: str - - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.subscription_id = subscription_id - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "autorestvalidationtest/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_vendor.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/__init__.py deleted file mode 100644 index 3be6ca519c0..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestValidationTest - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestValidationTest"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_client.py deleted file mode 100644 index 23fbeee22c4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_client.py +++ /dev/null @@ -1,76 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestValidationTestConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestValidationTest: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest. No server backend exists for these tests. - - :param subscription_id: Subscription ID. Required. - :type subscription_id: str - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - :keyword api_version: Api Version. Default value is "1.0.0". Note that overriding this default - value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, subscription_id: str, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestValidationTestConfiguration(subscription_id=subscription_id, **kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `validationlowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from validationlowlevel.rest import build_validation_of_method_parameters_request - >>> request = build_validation_of_method_parameters_request(resource_group_name, id, subscription_id, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestValidationTest": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_configuration.py deleted file mode 100644 index 0836f25710d..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_configuration.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestValidationTestConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestValidationTest. - - Note that all parameters used to create this instance are saved as instance - attributes. - - :param subscription_id: Subscription ID. Required. - :type subscription_id: str - :keyword api_version: Api Version. Default value is "1.0.0". Note that overriding this default - value may result in unsupported behavior. - :paramtype api_version: str - """ - - def __init__(self, subscription_id: str, **kwargs: Any) -> None: - super(AutoRestValidationTestConfiguration, self).__init__(**kwargs) - api_version = kwargs.pop("api_version", "1.0.0") # type: str - - if subscription_id is None: - raise ValueError("Parameter 'subscription_id' must not be None.") - - self.subscription_id = subscription_id - self.api_version = api_version - kwargs.setdefault("sdk_moniker", "autorestvalidationtest/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/rest/__init__.py deleted file mode 100644 index 4b6477de821..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/rest/__init__.py +++ /dev/null @@ -1,19 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_validation_of_method_parameters_request -from ._request_builders import build_validation_of_body_request -from ._request_builders import build_get_with_constant_in_path_request -from ._request_builders import build_post_with_constant_in_body_request - -__all__ = [ - "build_validation_of_method_parameters_request", - "build_validation_of_body_request", - "build_get_with_constant_in_path_request", - "build_post_with_constant_in_body_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/rest/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/rest/_request_builders.py deleted file mode 100644 index 35e897ebbf0..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/ValidationLowLevel/validationlowlevel/rest/_request_builders.py +++ /dev/null @@ -1,371 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, Optional, Union, overload - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from .._serialization import Serializer -from .._vendor import _format_url_section - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_validation_of_method_parameters_request( - resource_group_name: str, id: int, subscription_id: str, **kwargs: Any -) -> HttpRequest: - """Validates input parameters on the method. See swagger for details. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: Required string between 3 and 10 chars with pattern [a-zA-Z0-9]+. - Required. - :type resource_group_name: str - :param id: Required int multiple of 10 from 100 to 1000. Required. - :type id: int - :param subscription_id: Subscription ID. Required. - :type subscription_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - api_version = kwargs.pop("api_version", _params.pop("apiVersion", "1.0.0")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/fakepath/{subscriptionId}/{resourceGroupName}/{id}" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=10, min_length=3, pattern=r"[a-zA-Z0-9\']+" - ), - "id": _SERIALIZER.url("id", id, "int", maximum=1000, minimum=100, multiple=10), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["apiVersion"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -@overload -def build_validation_of_body_request( - resource_group_name: str, - id: int, - subscription_id: str, - *, - content_type: Optional[str] = None, - json: Optional[JSON] = None, - **kwargs: Any -) -> HttpRequest: - """Validates body parameters on the method. See swagger for details. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: Required string between 3 and 10 chars with pattern [a-zA-Z0-9]+. - Required. - :type resource_group_name: str - :param id: Required int multiple of 10 from 100 to 1000. Required. - :type id: int - :param subscription_id: Subscription ID. Required. - :type subscription_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Default value is None. - :paramtype json: JSON - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "capacity": 0, # Optional. Non required int betwen 0 and 100 exclusive. - "child": { - "constProperty": "constant", # Default value is "constant". Constant - string. Required. - "count": 0 # Optional. Count. - }, - "constChild": { - "constProperty": "constant", # Default value is "constant". Constant - string. Required. - "constProperty2": "constant2" # Default value is "constant2". - Constant string2. Required. - }, - "constInt": 0, # Default value is 0. Constant int. Required. - "constString": "constant", # Default value is "constant". Constant string. - Required. - "constStringAsEnum": "constant_string_as_enum", # Optional. Default value is - "constant_string_as_enum". Constant string as Enum. - "display_names": [ - "str" # Optional. Non required array of unique items from 0 to 6 - elements. - ], - "image": "str" # Optional. Image URL representing the product. - } - """ - - -@overload -def build_validation_of_body_request( - resource_group_name: str, - id: int, - subscription_id: str, - *, - content_type: Optional[str] = None, - content: Optional[IO] = None, - **kwargs: Any -) -> HttpRequest: - """Validates body parameters on the method. See swagger for details. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: Required string between 3 and 10 chars with pattern [a-zA-Z0-9]+. - Required. - :type resource_group_name: str - :param id: Required int multiple of 10 from 100 to 1000. Required. - :type id: int - :param subscription_id: Subscription ID. Required. - :type subscription_id: str - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Default value is None. - :paramtype content: IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_validation_of_body_request( - resource_group_name: str, id: int, subscription_id: str, **kwargs: Any -) -> HttpRequest: - """Validates body parameters on the method. See swagger for details. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param resource_group_name: Required string between 3 and 10 chars with pattern [a-zA-Z0-9]+. - Required. - :type resource_group_name: str - :param id: Required int multiple of 10 from 100 to 1000. Required. - :type id: int - :param subscription_id: Subscription ID. Required. - :type subscription_id: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - api_version = kwargs.pop("api_version", _params.pop("apiVersion", "1.0.0")) # type: str - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/fakepath/{subscriptionId}/{resourceGroupName}/{id}" - path_format_arguments = { - "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), - "resourceGroupName": _SERIALIZER.url( - "resource_group_name", resource_group_name, "str", max_length=10, min_length=3, pattern=r"[a-zA-Z0-9]+" - ), - "id": _SERIALIZER.url("id", id, "int", maximum=1000, minimum=100, multiple=10), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct parameters - _params["apiVersion"] = _SERIALIZER.query("api_version", api_version, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_with_constant_in_path_request(**kwargs: Any) -> HttpRequest: - """get_with_constant_in_path. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword constant_param: Default value is "constant". Note that overriding this default value - may result in unsupported behavior. - :paramtype constant_param: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - constant_param = kwargs.pop("constant_param", "constant") # type: str - # Construct URL - _url = "/validation/constantsInPath/{constantParam}/value" - path_format_arguments = { - "constantParam": _SERIALIZER.url("constant_param", constant_param, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - return HttpRequest(method="GET", url=_url, **kwargs) - - -@overload -def build_post_with_constant_in_body_request( - *, content_type: Optional[str] = None, json: Optional[JSON] = None, **kwargs: Any -) -> HttpRequest: - """post_with_constant_in_body. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :keyword json: Default value is None. - :paramtype json: JSON - :keyword constant_param: Default value is "constant". Note that overriding this default value - may result in unsupported behavior. - :paramtype constant_param: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "capacity": 0, # Optional. Non required int betwen 0 and 100 exclusive. - "child": { - "constProperty": "constant", # Default value is "constant". Constant - string. Required. - "count": 0 # Optional. Count. - }, - "constChild": { - "constProperty": "constant", # Default value is "constant". Constant - string. Required. - "constProperty2": "constant2" # Default value is "constant2". - Constant string2. Required. - }, - "constInt": 0, # Default value is 0. Constant int. Required. - "constString": "constant", # Default value is "constant". Constant string. - Required. - "constStringAsEnum": "constant_string_as_enum", # Optional. Default value is - "constant_string_as_enum". Constant string as Enum. - "display_names": [ - "str" # Optional. Non required array of unique items from 0 to 6 - elements. - ], - "image": "str" # Optional. Image URL representing the product. - } - """ - - -@overload -def build_post_with_constant_in_body_request( - *, content_type: Optional[str] = None, content: Optional[IO] = None, **kwargs: Any -) -> HttpRequest: - """post_with_constant_in_body. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :keyword content: Default value is None. - :paramtype content: IO - :keyword constant_param: Default value is "constant". Note that overriding this default value - may result in unsupported behavior. - :paramtype constant_param: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_post_with_constant_in_body_request(**kwargs: Any) -> HttpRequest: - """post_with_constant_in_body. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword constant_param: Default value is "constant". Note that overriding this default value - may result in unsupported behavior. - :paramtype constant_param: str - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :keyword json: Is either a model type or a IO type. Default value is None. - :paramtype json: JSON or IO - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - constant_param = kwargs.pop("constant_param", "constant") # type: str - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/validation/constantsInPath/{constantParam}/value" - path_format_arguments = { - "constantParam": _SERIALIZER.url("constant_param", constant_param, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/setup.py deleted file mode 100644 index cfe87fd191a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "autorestswaggerbatxmlservice" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="AutoRestSwaggerBATXMLService", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - Test Infrastructure for AutoRest Swagger BAT. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/__init__.py deleted file mode 100644 index 0808633e6cf..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATXMLService -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATXMLService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_client.py deleted file mode 100644 index eb29d02566f..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import AutoRestSwaggerBATXMLServiceConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATXMLService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATXMLServiceConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `xmlservicelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from xmlservicelowlevel.rest import xml - >>> request = xml.build_get_complex_type_ref_no_meta_request(**kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> AutoRestSwaggerBATXMLService - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_configuration.py deleted file mode 100644 index ff5722e2a21..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class AutoRestSwaggerBATXMLServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATXMLService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATXMLServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatxmlservice/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/__init__.py deleted file mode 100644 index 6517ad56fd4..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import AutoRestSwaggerBATXMLService - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["AutoRestSwaggerBATXMLService"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_client.py deleted file mode 100644 index 344b5675cd2..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import AutoRestSwaggerBATXMLServiceConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class AutoRestSwaggerBATXMLService: # pylint: disable=client-accepts-api-version-keyword - """Test Infrastructure for AutoRest Swagger BAT. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = AutoRestSwaggerBATXMLServiceConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `xmlservicelowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from xmlservicelowlevel.rest import xml - >>> request = xml.build_get_complex_type_ref_no_meta_request(**kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "AutoRestSwaggerBATXMLService": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_configuration.py deleted file mode 100644 index c6d89c576de..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class AutoRestSwaggerBATXMLServiceConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for AutoRestSwaggerBATXMLService. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(AutoRestSwaggerBATXMLServiceConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "autorestswaggerbatxmlservice/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/xml/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/xml/__init__.py deleted file mode 100644 index 01ebc1e433c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/xml/__init__.py +++ /dev/null @@ -1,79 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_complex_type_ref_no_meta_request -from ._request_builders import build_put_complex_type_ref_no_meta_request -from ._request_builders import build_get_complex_type_ref_with_meta_request -from ._request_builders import build_put_complex_type_ref_with_meta_request -from ._request_builders import build_get_simple_request -from ._request_builders import build_put_simple_request -from ._request_builders import build_get_wrapped_lists_request -from ._request_builders import build_put_wrapped_lists_request -from ._request_builders import build_get_headers_request -from ._request_builders import build_get_empty_list_request -from ._request_builders import build_put_empty_list_request -from ._request_builders import build_get_empty_wrapped_lists_request -from ._request_builders import build_put_empty_wrapped_lists_request -from ._request_builders import build_get_root_list_request -from ._request_builders import build_put_root_list_request -from ._request_builders import build_get_root_list_single_item_request -from ._request_builders import build_put_root_list_single_item_request -from ._request_builders import build_get_empty_root_list_request -from ._request_builders import build_put_empty_root_list_request -from ._request_builders import build_get_empty_child_element_request -from ._request_builders import build_put_empty_child_element_request -from ._request_builders import build_list_containers_request -from ._request_builders import build_get_service_properties_request -from ._request_builders import build_put_service_properties_request -from ._request_builders import build_get_acls_request -from ._request_builders import build_put_acls_request -from ._request_builders import build_list_blobs_request -from ._request_builders import build_json_input_request -from ._request_builders import build_json_output_request -from ._request_builders import build_get_xms_text_request -from ._request_builders import build_get_bytes_request -from ._request_builders import build_put_binary_request -from ._request_builders import build_get_uri_request -from ._request_builders import build_put_uri_request - -__all__ = [ - "build_get_complex_type_ref_no_meta_request", - "build_put_complex_type_ref_no_meta_request", - "build_get_complex_type_ref_with_meta_request", - "build_put_complex_type_ref_with_meta_request", - "build_get_simple_request", - "build_put_simple_request", - "build_get_wrapped_lists_request", - "build_put_wrapped_lists_request", - "build_get_headers_request", - "build_get_empty_list_request", - "build_put_empty_list_request", - "build_get_empty_wrapped_lists_request", - "build_put_empty_wrapped_lists_request", - "build_get_root_list_request", - "build_put_root_list_request", - "build_get_root_list_single_item_request", - "build_put_root_list_single_item_request", - "build_get_empty_root_list_request", - "build_put_empty_root_list_request", - "build_get_empty_child_element_request", - "build_put_empty_child_element_request", - "build_list_containers_request", - "build_get_service_properties_request", - "build_put_service_properties_request", - "build_get_acls_request", - "build_put_acls_request", - "build_list_blobs_request", - "build_json_input_request", - "build_json_output_request", - "build_get_xms_text_request", - "build_get_bytes_request", - "build_put_binary_request", - "build_get_uri_request", - "build_put_uri_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/xml/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/xml/_request_builders.py deleted file mode 100644 index 86615766b4c..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmlLowLevel/xmlservicelowlevel/rest/xml/_request_builders.py +++ /dev/null @@ -1,1289 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -import sys -from typing import Any, IO, List, Optional, Union, overload -from xml.etree import ElementTree as ET - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer - -if sys.version_info >= (3, 9): - from collections.abc import MutableMapping -else: - from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports -JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_complex_type_ref_no_meta_request(**kwargs: Any) -> HttpRequest: - """Get a complex type that has a ref to a complex type with no XML node. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/complex-type-ref-no-meta" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_complex_type_ref_no_meta_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Puts a complex type that has a ref to a complex type with no XML node. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: ET.Element - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = { - "RefToModel": { - "ID": "str" # Optional. The id of the res. - }, - "Something": "str" # Optional. Something else (just to avoid flattening). - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/xml/complex-type-ref-no-meta" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_complex_type_ref_with_meta_request(**kwargs: Any) -> HttpRequest: - """Get a complex type that has a ref to a complex type with XML node. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/complex-type-ref-with-meta" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_complex_type_ref_with_meta_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Puts a complex type that has a ref to a complex type with XML node. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: ET.Element - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = { - "RefToModel": { - "ID": "str" # Optional. The id of the res. - }, - "Something": "str" # Optional. Something else (just to avoid flattening). - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/xml/complex-type-ref-with-meta" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_simple_request(**kwargs: Any) -> HttpRequest: - """Get a simple XML document. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/simple" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_simple_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Put a simple XML document. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: ET.Element - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = { - "author": "str", # Optional. - "date": "str", # Optional. - "slides": [ - { - "items": [ - "str" # Optional. - ], - "title": "str", # Optional. - "type": "str" # Optional. - } - ], - "title": "str" # Optional. - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/simple" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_wrapped_lists_request(**kwargs: Any) -> HttpRequest: - """Get an XML document with multiple wrapped lists. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/wrapped-lists" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_wrapped_lists_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Put an XML document with multiple wrapped lists. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: ET.Element - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = { - "BadApples": [ - "str" # Optional. - ], - "GoodApples": [ - "str" # Optional. - ] - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/wrapped-lists" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_headers_request(**kwargs: Any) -> HttpRequest: - """Get strongly-typed response headers. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - # Construct URL - _url = "/xml/headers" - - return HttpRequest(method="GET", url=_url, **kwargs) - - -def build_get_empty_list_request(**kwargs: Any) -> HttpRequest: - """Get an empty list. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/empty-list" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_empty_list_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Puts an empty list. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: ET.Element - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = { - "author": "str", # Optional. - "date": "str", # Optional. - "slides": [ - { - "items": [ - "str" # Optional. - ], - "title": "str", # Optional. - "type": "str" # Optional. - } - ], - "title": "str" # Optional. - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/xml/empty-list" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_empty_wrapped_lists_request(**kwargs: Any) -> HttpRequest: - """Gets some empty wrapped lists. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/empty-wrapped-lists" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_empty_wrapped_lists_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Puts some empty wrapped lists. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: ET.Element - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = { - "BadApples": [ - "str" # Optional. - ], - "GoodApples": [ - "str" # Optional. - ] - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/xml/empty-wrapped-lists" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_root_list_request(**kwargs: Any) -> HttpRequest: - """Gets a list as the root element. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/root-list" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_root_list_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Puts a list as the root element. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: list[ET.Element] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = [ - { - "expiration": "2020-02-20 00:00:00", # Optional. The time at which - you should reconsider eating this banana. - "flavor": "str", # Optional. - "name": "str" # Optional. - } - ] - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/xml/root-list" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_root_list_single_item_request(**kwargs: Any) -> HttpRequest: - """Gets a list with a single item. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/root-list-single-item" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_root_list_single_item_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Puts a list with a single item. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: list[ET.Element] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = [ - { - "expiration": "2020-02-20 00:00:00", # Optional. The time at which - you should reconsider eating this banana. - "flavor": "str", # Optional. - "name": "str" # Optional. - } - ] - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/xml/root-list-single-item" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_empty_root_list_request(**kwargs: Any) -> HttpRequest: - """Gets an empty list as the root element. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/empty-root-list" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_empty_root_list_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Puts an empty list as the root element. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: list[ET.Element] - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = [ - { - "expiration": "2020-02-20 00:00:00", # Optional. The time at which - you should reconsider eating this banana. - "flavor": "str", # Optional. - "name": "str" # Optional. - } - ] - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/xml/empty-root-list" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_empty_child_element_request(**kwargs: Any) -> HttpRequest: - """Gets an XML document with an empty child element. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/empty-child-element" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_empty_child_element_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Puts a value with an empty child element. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: ET.Element - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = { - "expiration": "2020-02-20 00:00:00", # Optional. The time at which you - should reconsider eating this banana. - "flavor": "str", # Optional. - "name": "str" # Optional. - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/xml/empty-child-element" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_list_containers_request(**kwargs: Any) -> HttpRequest: - """Lists containers in a storage account. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword comp: Default value is "list". Note that overriding this default value may result in - unsupported behavior. - :paramtype comp: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp = kwargs.pop("comp", _params.pop("comp", "list")) # type: str - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/" - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_get_service_properties_request(**kwargs: Any) -> HttpRequest: - """Gets storage service properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword comp: Default value is "properties". Note that overriding this default value may - result in unsupported behavior. - :paramtype comp: str - :keyword restype: Default value is "service". Note that overriding this default value may - result in unsupported behavior. - :paramtype restype: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp = kwargs.pop("comp", _params.pop("comp", "properties")) # type: str - restype = kwargs.pop("restype", _params.pop("restype", "service")) # type: str - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/" - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_put_service_properties_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Puts storage service properties. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: ET.Element - :keyword comp: Default value is "properties". Note that overriding this default value may - result in unsupported behavior. - :paramtype comp: str - :keyword restype: Default value is "service". Note that overriding this default value may - result in unsupported behavior. - :paramtype restype: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = { - "Cors": [ - { - "AllowedHeaders": "str", # the request headers that the - origin domain may specify on the CORS request. Required. - "AllowedMethods": "str", # The methods (HTTP request verbs) - that the origin domain may use for a CORS request. (comma separated). - Required. - "AllowedOrigins": "str", # The origin domains that are - permitted to make a request against the storage service via CORS. The - origin domain is the domain from which the request originates. Note that - the origin must be an exact case-sensitive match with the origin that the - user age sends to the service. You can also use the wildcard character - '*' to allow all origin domains to make requests via CORS. Required. - "ExposedHeaders": "str", # The response headers that may be - sent in the response to the CORS request and exposed by the browser to - the request issuer. Required. - "MaxAgeInSeconds": 0 # The maximum amount time that a - browser should cache the preflight OPTIONS request. Required. - } - ], - "DefaultServiceVersion": "str", # Optional. The default version to use for - requests to the Blob service if an incoming request's version is not specified. - Possible values include version 2008-10-27 and all more recent versions. - "DeleteRetentionPolicy": { - "Days": 0, # Optional. Indicates the number of days that metrics or - logging or soft-deleted data should be retained. All data older than this - value will be deleted. - "Enabled": bool # Indicates whether a retention policy is enabled - for the storage service. Required. - }, - "HourMetrics": { - "Enabled": bool, # Indicates whether metrics are enabled for the - Blob service. Required. - "IncludeAPIs": bool, # Optional. Indicates whether metrics should - generate summary statistics for called API operations. - "RetentionPolicy": { - "Days": 0, # Optional. Indicates the number of days that - metrics or logging or soft-deleted data should be retained. All data - older than this value will be deleted. - "Enabled": bool # Indicates whether a retention policy is - enabled for the storage service. Required. - }, - "Version": "str" # Optional. The version of Storage Analytics to - configure. - }, - "Logging": { - "Delete": bool, # Indicates whether all delete requests should be - logged. Required. - "Read": bool, # Indicates whether all read requests should be - logged. Required. - "RetentionPolicy": { - "Days": 0, # Optional. Indicates the number of days that - metrics or logging or soft-deleted data should be retained. All data - older than this value will be deleted. - "Enabled": bool # Indicates whether a retention policy is - enabled for the storage service. Required. - }, - "Version": "str", # The version of Storage Analytics to configure. - Required. - "Write": bool # Indicates whether all write requests should be - logged. Required. - }, - "MinuteMetrics": { - "Enabled": bool, # Indicates whether metrics are enabled for the - Blob service. Required. - "IncludeAPIs": bool, # Optional. Indicates whether metrics should - generate summary statistics for called API operations. - "RetentionPolicy": { - "Days": 0, # Optional. Indicates the number of days that - metrics or logging or soft-deleted data should be retained. All data - older than this value will be deleted. - "Enabled": bool # Indicates whether a retention policy is - enabled for the storage service. Required. - }, - "Version": "str" # Optional. The version of Storage Analytics to - configure. - } - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp = kwargs.pop("comp", _params.pop("comp", "properties")) # type: str - restype = kwargs.pop("restype", _params.pop("restype", "service")) # type: str - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/xml/" - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_get_acls_request(**kwargs: Any) -> HttpRequest: - """Gets storage ACLs for a container. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword comp: Default value is "acl". Note that overriding this default value may result in - unsupported behavior. - :paramtype comp: str - :keyword restype: Default value is "container". Note that overriding this default value may - result in unsupported behavior. - :paramtype restype: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp = kwargs.pop("comp", _params.pop("comp", "acl")) # type: str - restype = kwargs.pop("restype", _params.pop("restype", "container")) # type: str - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/mycontainer" - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -def build_put_acls_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Puts storage ACLs for a container. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: list[ET.Element] - :keyword comp: Default value is "acl". Note that overriding this default value may result in - unsupported behavior. - :paramtype comp: str - :keyword restype: Default value is "container". Note that overriding this default value may - result in unsupported behavior. - :paramtype restype: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = [ - { - "AccessPolicy": { - "Expiry": "2020-02-20 00:00:00", # the date-time the policy - expires. Required. - "Permission": "str", # the permissions for the acl policy. - Required. - "Start": "2020-02-20 00:00:00" # the date-time the policy is - active. Required. - }, - "Id": "str" # a unique id. Required. - } - ] - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp = kwargs.pop("comp", _params.pop("comp", "acl")) # type: str - restype = kwargs.pop("restype", _params.pop("restype", "container")) # type: str - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/xml/mycontainer" - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, content=content, **kwargs) - - -def build_list_blobs_request(**kwargs: Any) -> HttpRequest: - """Lists blobs in a storage container. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword comp: Default value is "list". Note that overriding this default value may result in - unsupported behavior. - :paramtype comp: str - :keyword restype: Default value is "container". Note that overriding this default value may - result in unsupported behavior. - :paramtype restype: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - comp = kwargs.pop("comp", _params.pop("comp", "list")) # type: str - restype = kwargs.pop("restype", _params.pop("restype", "container")) # type: str - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/mycontainer" - - # Construct parameters - _params["comp"] = _SERIALIZER.query("comp", comp, "str") - _params["restype"] = _SERIALIZER.query("restype", restype, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) - - -@overload -def build_json_input_request(*, json: JSON, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """A Swagger with XML that has one operation that takes JSON as input. You need to send the ID - number 42. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Required. - :paramtype json: JSON - :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - json = { - "id": 0 # Optional. - } - """ - - -@overload -def build_json_input_request(*, content: IO, content_type: Optional[str] = None, **kwargs: Any) -> HttpRequest: - """A Swagger with XML that has one operation that takes JSON as input. You need to send the ID - number 42. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: IO - :keyword content_type: Body Parameter content-type. Content type parameter for binary body. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - -def build_json_input_request(**kwargs: Any) -> HttpRequest: - """A Swagger with XML that has one operation that takes JSON as input. You need to send the ID - number 42. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword json: Is either a model type or a IO type. Required. - :paramtype json: JSON or IO - :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. - Default value is None. - :paramtype content_type: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - # Construct URL - _url = "/xml/jsoninput" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, **kwargs) - - -def build_json_output_request(**kwargs: Any) -> HttpRequest: - """A Swagger with XML that has one operation that returns JSON. ID number 42. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/xml/jsonoutput" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_xms_text_request(**kwargs: Any) -> HttpRequest: - """Get back an XML object with an x-ms-text property, which should translate to the returned - object's 'language' property being 'english' and its 'content' property being 'I am text'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/x-ms-text" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_get_bytes_request(**kwargs: Any) -> HttpRequest: - """Get an XML document with binary property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/bytes" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_binary_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Put an XML document with binary property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: ET.Element - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = { - "Bytes": bytes("bytes", encoding="utf-8") # Optional. - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/bytes" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) - - -def build_get_uri_request(**kwargs: Any) -> HttpRequest: - """Get an XML document with uri property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/url" - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_put_uri_request(*, content: Any, **kwargs: Any) -> HttpRequest: - """Put an XML document with uri property. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword content: Required. - :paramtype content: ET.Element - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - - Example: - .. code-block:: python - - # JSON input template you can fill out and use as your body input. - content = { - "Url": "str" # Optional. - } - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - content_type = kwargs.pop("content_type", _headers.pop("Content-Type", None)) # type: Optional[str] - accept = _headers.pop("Accept", "application/xml") - - # Construct URL - _url = "/xml/url" - - # Construct headers - if content_type is not None: - _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="PUT", url=_url, headers=_headers, content=content, **kwargs) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/setup.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/setup.py deleted file mode 100644 index 75167125693..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/setup.py +++ /dev/null @@ -1,30 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -# coding: utf-8 -from setuptools import setup, find_packages - - -PACKAGE_NAME = "xmserrorresponseextensions" -version = "0.1.0" -setup( - name=PACKAGE_NAME, - version=version, - description="XMSErrorResponseExtensions", - author_email="", - url="", - keywords="azure, azure sdk", - packages=find_packages(), - include_package_data=True, - install_requires=[ - "isodate>=0.6.1", - "azure-core<2.0.0,>=1.24.0", - ], - long_description="""\ - XMS Error Response Extensions. - """, -) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/__init__.py deleted file mode 100644 index 7c4bd75a50a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/__init__.py +++ /dev/null @@ -1,24 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import XMSErrorResponseExtensions -from ._version import VERSION - -__version__ = VERSION - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["XMSErrorResponseExtensions"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_client.py deleted file mode 100644 index 18a452d252a..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_client.py +++ /dev/null @@ -1,74 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, TYPE_CHECKING - -from azure.core import PipelineClient -from azure.core.rest import HttpRequest, HttpResponse - -from ._configuration import XMSErrorResponseExtensionsConfiguration -from ._serialization import Deserializer, Serializer - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class XMSErrorResponseExtensions: # pylint: disable=client-accepts-api-version-keyword - """XMS Error Response Extensions. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = XMSErrorResponseExtensionsConfiguration(**kwargs) - self._client = PipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> HttpResponse: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `xmserrorresponselowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from xmserrorresponselowlevel.rest import pet - >>> request = pet.build_get_pet_by_id_request(pet_id, **kwargs) - - >>> response = client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.HttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - def close(self): - # type: () -> None - self._client.close() - - def __enter__(self): - # type: () -> XMSErrorResponseExtensions - self._client.__enter__() - return self - - def __exit__(self, *exc_details): - # type: (Any) -> None - self._client.__exit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_configuration.py deleted file mode 100644 index d8bbf515bf2..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_configuration.py +++ /dev/null @@ -1,42 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from ._version import VERSION - - -class XMSErrorResponseExtensionsConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for XMSErrorResponseExtensions. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(XMSErrorResponseExtensionsConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "xmserrorresponseextensions/{}".format(VERSION)) - self._configure(**kwargs) - - def _configure( - self, **kwargs # type: Any - ): - # type: (...) -> 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_serialization.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_serialization.py deleted file mode 100644 index 7daa7a447db..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_serialization.py +++ /dev/null @@ -1,1970 +0,0 @@ -# -------------------------------------------------------------------------- -# -# Copyright (c) Microsoft Corporation. All rights reserved. -# -# The MIT License (MIT) -# -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the ""Software""), to -# deal in the Software without restriction, including without limitation the -# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -# sell copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -# IN THE SOFTWARE. -# -# -------------------------------------------------------------------------- - -# pylint: skip-file - -from base64 import b64decode, b64encode -import calendar -import datetime -import decimal -import email -from enum import Enum -import json -import logging -import re -import sys -import codecs - -try: - from urllib import quote # type: ignore -except ImportError: - from urllib.parse import quote # type: ignore -import xml.etree.ElementTree as ET - -import isodate - -from typing import Dict, Any, cast, TYPE_CHECKING - -from azure.core.exceptions import DeserializationError, SerializationError, raise_with_traceback - -_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") - -if TYPE_CHECKING: - from typing import Optional, Union, AnyStr, IO, Mapping - - -class RawDeserializer: - - # Accept "text" because we're open minded people... - JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") - - # Name used in context - CONTEXT_NAME = "deserialized_data" - - @classmethod - def deserialize_from_text(cls, data, content_type=None): - # type: (Optional[Union[AnyStr, IO]], Optional[str]) -> Any - """Decode data according to content-type. - - Accept a stream of data as well, but will be load at once in memory for now. - - If no content-type, will return the string version (not bytes, not stream) - - :param data: Input, could be bytes or stream (will be decoded with UTF8) or text - :type data: str or bytes or IO - :param str content_type: The content type. - """ - if hasattr(data, "read"): - # Assume a stream - data = cast(IO, data).read() - - if isinstance(data, bytes): - data_as_str = data.decode(encoding="utf-8-sig") - else: - # Explain to mypy the correct type. - data_as_str = cast(str, data) - - # Remove Byte Order Mark if present in string - data_as_str = data_as_str.lstrip(_BOM) - - if content_type is None: - return data - - if cls.JSON_REGEXP.match(content_type): - try: - return json.loads(data_as_str) - except ValueError as err: - raise DeserializationError("JSON is invalid: {}".format(err), err) - elif "xml" in (content_type or []): - try: - - try: - if isinstance(data, unicode): # type: ignore - # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string - data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore - except NameError: - pass - - return ET.fromstring(data_as_str) - except ET.ParseError: - # It might be because the server has an issue, and returned JSON with - # content-type XML.... - # So let's try a JSON load, and if it's still broken - # let's flow the initial exception - def _json_attemp(data): - try: - return True, json.loads(data) - except ValueError: - return False, None # Don't care about this one - - success, json_result = _json_attemp(data) - if success: - return json_result - # If i'm here, it's not JSON, it's not XML, let's scream - # and raise the last context in this block (the XML exception) - # The function hack is because Py2.7 messes up with exception - # context otherwise. - _LOGGER.critical("Wasn't XML not JSON, failing") - raise_with_traceback(DeserializationError, "XML is invalid") - raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) - - @classmethod - def deserialize_from_http_generics(cls, body_bytes, headers): - # type: (Optional[Union[AnyStr, IO]], Mapping) -> Any - """Deserialize from HTTP response. - - Use bytes and headers to NOT use any requests/aiohttp or whatever - specific implementation. - Headers will tested for "content-type" - """ - # Try to use content-type from headers if available - content_type = None - if "content-type" in headers: - content_type = headers["content-type"].split(";")[0].strip().lower() - # Ouch, this server did not declare what it sent... - # Let's guess it's JSON... - # Also, since Autorest was considering that an empty body was a valid JSON, - # need that test as well.... - else: - content_type = "application/json" - - if body_bytes: - return cls.deserialize_from_text(body_bytes, content_type) - return None - - -try: - basestring # type: ignore - unicode_str = unicode # type: ignore -except NameError: - basestring = str # type: ignore - unicode_str = str # type: ignore - -_LOGGER = logging.getLogger(__name__) - -try: - _long_type = long # type: ignore -except NameError: - _long_type = int - - -class UTC(datetime.tzinfo): - """Time Zone info for handling UTC""" - - def utcoffset(self, dt): - """UTF offset for UTC is 0.""" - return datetime.timedelta(0) - - def tzname(self, dt): - """Timestamp representation.""" - return "Z" - - def dst(self, dt): - """No daylight saving for UTC.""" - return datetime.timedelta(hours=1) - - -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 - :param datetime.timedelta offset: offset in timedelta format - """ - - def __init__(self, offset): - self.__offset = offset - - def utcoffset(self, dt): - return self.__offset - - def tzname(self, dt): - return str(self.__offset.total_seconds() / 3600) - - def __repr__(self): - return "".format(self.tzname(None)) - - def dst(self, dt): - return datetime.timedelta(0) - - def __getinitargs__(self): - return (self.__offset,) - - -try: - from datetime import timezone - - TZ_UTC = timezone.utc # type: ignore -except ImportError: - TZ_UTC = UTC() # type: ignore - -_FLATTEN = re.compile(r"(? y, - "minimum": lambda x, y: x < y, - "maximum": lambda x, y: x > y, - "minimum_ex": lambda x, y: x <= y, - "maximum_ex": lambda x, y: x >= y, - "min_items": lambda x, y: len(x) < y, - "max_items": lambda x, y: len(x) > y, - "pattern": lambda x, y: not re.match(y, x, re.UNICODE), - "unique": lambda x, y: len(x) != len(set(x)), - "multiple": lambda x, y: x % y != 0, - } - - def __init__(self, classes=None): - self.serialize_type = { - "iso-8601": Serializer.serialize_iso, - "rfc-1123": Serializer.serialize_rfc, - "unix-time": Serializer.serialize_unix, - "duration": Serializer.serialize_duration, - "date": Serializer.serialize_date, - "time": Serializer.serialize_time, - "decimal": Serializer.serialize_decimal, - "long": Serializer.serialize_long, - "bytearray": Serializer.serialize_bytearray, - "base64": Serializer.serialize_base64, - "object": self.serialize_object, - "[]": self.serialize_iter, - "{}": self.serialize_dict, - } - self.dependencies = dict(classes) if classes else {} - self.key_transformer = full_restapi_key_transformer - self.client_side_validation = True - - def _serialize(self, target_obj, data_type=None, **kwargs): - """Serialize data into a string according to type. - - :param target_obj: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str, dict - :raises: SerializationError if serialization fails. - """ - key_transformer = kwargs.get("key_transformer", self.key_transformer) - keep_readonly = kwargs.get("keep_readonly", False) - if target_obj is None: - return None - - attr_name = None - class_name = target_obj.__class__.__name__ - - if data_type: - return self.serialize_data(target_obj, data_type, **kwargs) - - if not hasattr(target_obj, "_attribute_map"): - data_type = type(target_obj).__name__ - if data_type in self.basic_types.values(): - return self.serialize_data(target_obj, data_type, **kwargs) - - # Force "is_xml" kwargs if we detect a XML model - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) - - serialized = {} - if is_xml_model_serialization: - serialized = target_obj._create_xml_node() - try: - attributes = target_obj._attribute_map - for attr, attr_desc in attributes.items(): - attr_name = attr - if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): - continue - - if attr_name == "additional_properties" and attr_desc["key"] == "": - if target_obj.additional_properties is not None: - serialized.update(target_obj.additional_properties) - continue - try: - - orig_attr = getattr(target_obj, attr) - if is_xml_model_serialization: - pass # Don't provide "transformer" for XML for now. Keep "orig_attr" - else: # JSON - keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) - keys = keys if isinstance(keys, list) else [keys] - - kwargs["serialization_ctxt"] = attr_desc - new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) - - if is_xml_model_serialization: - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - xml_prefix = xml_desc.get("prefix", None) - xml_ns = xml_desc.get("ns", None) - if xml_desc.get("attr", False): - if xml_ns: - ET.register_namespace(xml_prefix, xml_ns) - xml_name = "{}{}".format(xml_ns, xml_name) - serialized.set(xml_name, new_attr) - continue - if xml_desc.get("text", False): - serialized.text = new_attr - continue - if isinstance(new_attr, list): - serialized.extend(new_attr) - elif isinstance(new_attr, ET.Element): - # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. - if "name" not in getattr(orig_attr, "_xml_map", {}): - splitted_tag = new_attr.tag.split("}") - if len(splitted_tag) == 2: # Namespace - new_attr.tag = "}".join([splitted_tag[0], xml_name]) - else: - new_attr.tag = xml_name - serialized.append(new_attr) - else: # That's a basic type - # Integrate namespace if necessary - local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) - local_node.text = unicode_str(new_attr) - serialized.append(local_node) - else: # JSON - for k in reversed(keys): - unflattened = {k: new_attr} - new_attr = unflattened - - _new_attr = new_attr - _serialized = serialized - for k in keys: - if k not in _serialized: - _serialized.update(_new_attr) - _new_attr = _new_attr[k] - _serialized = _serialized[k] - except ValueError: - continue - - except (AttributeError, KeyError, TypeError) as err: - msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) - raise_with_traceback(SerializationError, msg, err) - else: - return serialized - - def body(self, data, data_type, **kwargs): - """Serialize data intended for a request body. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: dict - :raises: SerializationError if serialization fails. - :raises: ValueError if data is None - """ - - # Just in case this is a dict - internal_data_type = data_type.strip("[]{}") - internal_data_type = self.dependencies.get(internal_data_type, None) - try: - is_xml_model_serialization = kwargs["is_xml"] - except KeyError: - if internal_data_type and issubclass(internal_data_type, Model): - is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) - else: - is_xml_model_serialization = False - if internal_data_type and not isinstance(internal_data_type, Enum): - try: - deserializer = Deserializer(self.dependencies) - # Since it's on serialization, it's almost sure that format is not JSON REST - # We're not able to deal with additional properties for now. - deserializer.additional_properties_detection = False - if is_xml_model_serialization: - deserializer.key_extractors = [ - attribute_key_case_insensitive_extractor, - ] - else: - deserializer.key_extractors = [ - rest_key_case_insensitive_extractor, - attribute_key_case_insensitive_extractor, - last_rest_key_case_insensitive_extractor, - ] - data = deserializer._deserialize(data_type, data) - except DeserializationError as err: - raise_with_traceback(SerializationError, "Unable to build a model: " + str(err), err) - - return self._serialize(data, data_type, **kwargs) - - def url(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL path. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return output - - def query(self, name, data, data_type, **kwargs): - """Serialize data intended for a URL query. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - # 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] - data = [self.serialize_data(d, internal_data_type, **kwargs) if d is not None else "" for d in data] - if not kwargs.get("skip_quote", False): - data = [quote(str(d), safe="") for d in data] - return str(self.serialize_iter(data, internal_data_type, **kwargs)) - - # Not a list, regular serialization - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - if kwargs.get("skip_quote") is True: - output = str(output) - else: - output = quote(str(output), safe="") - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def header(self, name, data, data_type, **kwargs): - """Serialize data intended for a request header. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :rtype: str - :raises: TypeError if serialization fails. - :raises: ValueError if data is None - """ - try: - if data_type in ["[str]"]: - data = ["" if d is None else d for d in data] - - output = self.serialize_data(data, data_type, **kwargs) - if data_type == "bool": - output = json.dumps(output) - except SerializationError: - raise TypeError("{} must be type {}.".format(name, data_type)) - else: - return str(output) - - def serialize_data(self, data, data_type, **kwargs): - """Serialize generic data according to supplied data type. - - :param data: The data to be serialized. - :param str data_type: The type to be serialized from. - :param bool required: Whether it's essential that the data not be - empty or None - :raises: AttributeError if required data is None. - :raises: ValueError if data is None - :raises: SerializationError if serialization fails. - """ - if data is None: - raise ValueError("No value for given attribute") - - try: - if data_type in self.basic_types.values(): - return self.serialize_basic(data, data_type, **kwargs) - - elif data_type in self.serialize_type: - return self.serialize_type[data_type](data, **kwargs) - - # If dependencies is empty, try with current data class - # It has to be a subclass of Enum anyway - enum_type = self.dependencies.get(data_type, data.__class__) - if issubclass(enum_type, Enum): - return Serializer.serialize_enum(data, enum_obj=enum_type) - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.serialize_type: - return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) - - except (ValueError, TypeError) as err: - msg = "Unable to serialize value: {!r} as type: {!r}." - raise_with_traceback(SerializationError, msg.format(data, data_type), err) - else: - return self._serialize(data, **kwargs) - - @classmethod - def _get_custom_serializers(cls, data_type, **kwargs): - custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) - if custom_serializer: - return custom_serializer - if kwargs.get("is_xml", False): - return cls._xml_basic_types_serializers.get(data_type) - - @classmethod - def serialize_basic(cls, data, data_type, **kwargs): - """Serialize basic builting data type. - Serializes objects to str, int, float or bool. - - Possible kwargs: - - basic_types_serializers dict[str, callable] : If set, use the callable as serializer - - is_xml bool : If set, use xml_basic_types_serializers - - :param data: Object to be serialized. - :param str data_type: Type of object in the iterable. - """ - custom_serializer = cls._get_custom_serializers(data_type, **kwargs) - if custom_serializer: - return custom_serializer(data) - if data_type == "str": - return cls.serialize_unicode(data) - return eval(data_type)(data) - - @classmethod - def serialize_unicode(cls, data): - """Special handling for serializing unicode strings in Py2. - Encode to UTF-8 if unicode, otherwise handle as a str. - - :param data: Object to be serialized. - :rtype: str - """ - try: # If I received an enum, return its value - return data.value - except AttributeError: - pass - - try: - if isinstance(data, unicode): - # Don't change it, JSON and XML ElementTree are totally able - # to serialize correctly u'' strings - return data - except NameError: - return str(data) - else: - return str(data) - - def serialize_iter(self, data, iter_type, div=None, **kwargs): - """Serialize iterable. - - Supported kwargs: - - serialization_ctxt dict : The current entry of _attribute_map, or same format. - serialization_ctxt['type'] should be same as data_type. - - is_xml bool : If set, serialize as XML - - :param list attr: Object to be serialized. - :param str iter_type: Type of object in the iterable. - :param bool required: Whether the objects in the iterable must - not be None or empty. - :param str div: If set, this str will be used to combine the elements - in the iterable into a combined string. Default is 'None'. - :rtype: list, str - """ - if isinstance(data, str): - raise SerializationError("Refuse str type as a valid iter type.") - - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - is_xml = kwargs.get("is_xml", False) - - serialized = [] - for d in data: - try: - serialized.append(self.serialize_data(d, iter_type, **kwargs)) - except ValueError: - serialized.append(None) - - if div: - serialized = ["" if s is None else str(s) for s in serialized] - serialized = div.join(serialized) - - if "xml" in serialization_ctxt or is_xml: - # XML serialization is more complicated - xml_desc = serialization_ctxt.get("xml", {}) - xml_name = xml_desc.get("name") - if not xml_name: - xml_name = serialization_ctxt["key"] - - # Create a wrap node if necessary (use the fact that Element and list have "append") - is_wrapped = xml_desc.get("wrapped", False) - node_name = xml_desc.get("itemsName", xml_name) - if is_wrapped: - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - else: - final_result = [] - # All list elements to "local_node" - for el in serialized: - if isinstance(el, ET.Element): - el_node = el - else: - el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - if el is not None: # Otherwise it writes "None" :-p - el_node.text = str(el) - final_result.append(el_node) - return final_result - return serialized - - def serialize_dict(self, attr, dict_type, **kwargs): - """Serialize a dictionary of objects. - - :param dict attr: Object to be serialized. - :param str dict_type: Type of object in the dictionary. - :param bool required: Whether the objects in the dictionary must - not be None or empty. - :rtype: dict - """ - serialization_ctxt = kwargs.get("serialization_ctxt", {}) - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - - if "xml" in serialization_ctxt: - # XML serialization is more complicated - xml_desc = serialization_ctxt["xml"] - xml_name = xml_desc["name"] - - final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) - for key, value in serialized.items(): - ET.SubElement(final_result, key).text = value - return final_result - - return serialized - - def serialize_object(self, attr, **kwargs): - """Serialize a generic object. - This will be handled as a dictionary. If object passed in is not - a basic type (str, int, float, dict, list) it will simply be - cast to str. - - :param dict attr: Object to be serialized. - :rtype: dict or str - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - return attr - obj_type = type(attr) - if obj_type in self.basic_types: - return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) - if obj_type is _long_type: - return self.serialize_long(attr) - if obj_type is unicode_str: - return self.serialize_unicode(attr) - if obj_type is datetime.datetime: - return self.serialize_iso(attr) - if obj_type is datetime.date: - return self.serialize_date(attr) - if obj_type is datetime.time: - return self.serialize_time(attr) - if obj_type is datetime.timedelta: - return self.serialize_duration(attr) - if obj_type is decimal.Decimal: - return self.serialize_decimal(attr) - - # If it's a model or I know this dependency, serialize as a Model - elif obj_type in self.dependencies.values() or isinstance(attr, Model): - return self._serialize(attr) - - if obj_type == dict: - serialized = {} - for key, value in attr.items(): - try: - serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) - except ValueError: - serialized[self.serialize_unicode(key)] = None - return serialized - - if obj_type == list: - serialized = [] - for obj in attr: - try: - serialized.append(self.serialize_object(obj, **kwargs)) - except ValueError: - pass - return serialized - return str(attr) - - @staticmethod - def serialize_enum(attr, enum_obj=None): - try: - result = attr.value - except AttributeError: - result = attr - try: - enum_obj(result) - return result - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(attr).lower(): - return enum_value.value - error = "{!r} is not valid value for enum {!r}" - raise SerializationError(error.format(attr, enum_obj)) - - @staticmethod - def serialize_bytearray(attr, **kwargs): - """Serialize bytearray into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - return b64encode(attr).decode() - - @staticmethod - def serialize_base64(attr, **kwargs): - """Serialize str into base-64 string. - - :param attr: Object to be serialized. - :rtype: str - """ - encoded = b64encode(attr).decode("ascii") - return encoded.strip("=").replace("+", "-").replace("/", "_") - - @staticmethod - def serialize_decimal(attr, **kwargs): - """Serialize Decimal object to float. - - :param attr: Object to be serialized. - :rtype: float - """ - return float(attr) - - @staticmethod - def serialize_long(attr, **kwargs): - """Serialize long (Py2) or int (Py3). - - :param attr: Object to be serialized. - :rtype: int/long - """ - return _long_type(attr) - - @staticmethod - def serialize_date(attr, **kwargs): - """Serialize Date object into ISO-8601 formatted string. - - :param Date attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_date(attr) - t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) - return t - - @staticmethod - def serialize_time(attr, **kwargs): - """Serialize Time object into ISO-8601 formatted string. - - :param datetime.time attr: Object to be serialized. - :rtype: str - """ - 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 - - @staticmethod - def serialize_duration(attr, **kwargs): - """Serialize TimeDelta object into ISO-8601 formatted string. - - :param TimeDelta attr: Object to be serialized. - :rtype: str - """ - if isinstance(attr, str): - attr = isodate.parse_duration(attr) - return isodate.duration_isoformat(attr) - - @staticmethod - def serialize_rfc(attr, **kwargs): - """Serialize Datetime object into RFC-1123 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: TypeError if format invalid. - """ - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - except AttributeError: - raise TypeError("RFC1123 object must be valid Datetime object.") - - return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( - Serializer.days[utc.tm_wday], - utc.tm_mday, - Serializer.months[utc.tm_mon], - utc.tm_year, - utc.tm_hour, - utc.tm_min, - utc.tm_sec, - ) - - @staticmethod - def serialize_iso(attr, **kwargs): - """Serialize Datetime object into ISO-8601 formatted string. - - :param Datetime attr: Object to be serialized. - :rtype: str - :raises: SerializationError if format invalid. - """ - if isinstance(attr, str): - attr = isodate.parse_datetime(attr) - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - utc = attr.utctimetuple() - 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") - if 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" - except (ValueError, OverflowError) as err: - msg = "Unable to serialize datetime object." - raise_with_traceback(SerializationError, msg, err) - except AttributeError as err: - msg = "ISO-8601 object must be valid Datetime object." - raise_with_traceback(TypeError, msg, err) - - @staticmethod - def serialize_unix(attr, **kwargs): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param Datetime attr: Object to be serialized. - :rtype: int - :raises: SerializationError if format invalid - """ - if isinstance(attr, int): - return attr - try: - if not attr.tzinfo: - _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") - return int(calendar.timegm(attr.utctimetuple())) - except AttributeError: - raise TypeError("Unix time object must be valid Datetime object.") - - -def rest_key_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = working_data.get(working_key, data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - return working_data.get(key) - - -def rest_key_case_insensitive_extractor(attr, attr_desc, data): - key = attr_desc["key"] - working_data = data - - while "." in key: - dict_keys = _FLATTEN.split(key) - if len(dict_keys) == 1: - key = _decode_attribute_map_key(dict_keys[0]) - break - working_key = _decode_attribute_map_key(dict_keys[0]) - working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) - if working_data is None: - # If at any point while following flatten JSON path see None, it means - # that all properties under are None as well - # https://github.com/Azure/msrest-for-python/issues/197 - return None - key = ".".join(dict_keys[1:]) - - if working_data: - return attribute_key_case_insensitive_extractor(key, None, working_data) - - -def last_rest_key_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key.""" - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_extractor(dict_keys[-1], None, data) - - -def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): - """Extract the attribute in "data" based on the last part of the JSON path key. - - This is the case insensitive version of "last_rest_key_extractor" - """ - key = attr_desc["key"] - dict_keys = _FLATTEN.split(key) - return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) - - -def attribute_key_extractor(attr, _, data): - return data.get(attr) - - -def attribute_key_case_insensitive_extractor(attr, _, data): - found_key = None - lower_attr = attr.lower() - for key in data: - if lower_attr == key.lower(): - found_key = key - break - - return data.get(found_key) - - -def _extract_name_from_internal_type(internal_type): - """Given an internal type XML description, extract correct XML name with namespace. - - :param dict internal_type: An model type - :rtype: tuple - :returns: A tuple XML name + namespace dict - """ - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - xml_name = internal_type_xml_map.get("name", internal_type.__name__) - xml_ns = internal_type_xml_map.get("ns", None) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - return xml_name - - -def xml_key_extractor(attr, attr_desc, data): - if isinstance(data, dict): - return None - - # Test if this model is XML ready first - if not isinstance(data, ET.Element): - return None - - xml_desc = attr_desc.get("xml", {}) - xml_name = xml_desc.get("name", attr_desc["key"]) - - # Look for a children - is_iter_type = attr_desc["type"].startswith("[") - is_wrapped = xml_desc.get("wrapped", False) - internal_type = attr_desc.get("internalType", None) - internal_type_xml_map = getattr(internal_type, "_xml_map", {}) - - # Integrate namespace if necessary - xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) - if xml_ns: - xml_name = "{}{}".format(xml_ns, xml_name) - - # If it's an attribute, that's simple - if xml_desc.get("attr", False): - return data.get(xml_name) - - # If it's x-ms-text, that's simple too - if xml_desc.get("text", False): - return data.text - - # Scenario where I take the local name: - # - Wrapped node - # - Internal type is an enum (considered basic types) - # - Internal type has no XML/Name node - if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): - children = data.findall(xml_name) - # If internal type has a local name and it's not a list, I use that name - elif not is_iter_type and internal_type and "name" in internal_type_xml_map: - xml_name = _extract_name_from_internal_type(internal_type) - children = data.findall(xml_name) - # That's an array - else: - if internal_type: # Complex type, ignore itemsName and use the complex type name - items_name = _extract_name_from_internal_type(internal_type) - else: - items_name = xml_desc.get("itemsName", xml_name) - children = data.findall(items_name) - - if len(children) == 0: - if is_iter_type: - if is_wrapped: - return None # is_wrapped no node, we want None - else: - return [] # not wrapped, assume empty list - return None # Assume it's not there, maybe an optional node. - - # If is_iter_type and not wrapped, return all found children - if is_iter_type: - if not is_wrapped: - return children - else: # Iter and wrapped, should have found one node only (the wrap one) - if len(children) != 1: - raise DeserializationError( - "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( - xml_name - ) - ) - return list(children[0]) # Might be empty list and that's ok. - - # Here it's not a itertype, we should have found one element only or empty - if len(children) > 1: - raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) - return children[0] - - -class Deserializer(object): - """Response object model deserializer. - - :param dict classes: Class type dictionary for deserializing complex types. - :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. - """ - - basic_types = {str: "str", int: "int", bool: "bool", float: "float"} - - 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=None): - self.deserialize_type = { - "iso-8601": Deserializer.deserialize_iso, - "rfc-1123": Deserializer.deserialize_rfc, - "unix-time": Deserializer.deserialize_unix, - "duration": Deserializer.deserialize_duration, - "date": Deserializer.deserialize_date, - "time": Deserializer.deserialize_time, - "decimal": Deserializer.deserialize_decimal, - "long": Deserializer.deserialize_long, - "bytearray": Deserializer.deserialize_bytearray, - "base64": Deserializer.deserialize_base64, - "object": self.deserialize_object, - "[]": self.deserialize_iter, - "{}": self.deserialize_dict, - } - self.deserialize_expected_types = { - "duration": (isodate.Duration, datetime.timedelta), - "iso-8601": (datetime.datetime), - } - self.dependencies = dict(classes) if classes else {} - self.key_extractors = [rest_key_extractor, xml_key_extractor] - # Additional properties only works if the "rest_key_extractor" is used to - # extract the keys. Making it to work whatever the key extractor is too much - # complicated, with no real scenario for now. - # So adding a flag to disable additional properties detection. This flag should be - # used if your expect the deserialization to NOT come from a JSON REST syntax. - # Otherwise, result are unexpected - self.additional_properties_detection = True - - def __call__(self, target_obj, response_data, content_type=None): - """Call the deserializer to process a REST response. - - :param str target_obj: Target data type to deserialize to. - :param requests.Response response_data: REST response object. - :param str content_type: Swagger "produces" if available. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - data = self._unpack_content(response_data, content_type) - return self._deserialize(target_obj, data) - - def _deserialize(self, target_obj, data): - """Call the deserializer on a model. - - Data needs to be already deserialized as JSON or XML ElementTree - - :param str target_obj: Target data type to deserialize to. - :param object data: Object to deserialize. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - # This is already a model, go recursive just in case - if hasattr(data, "_attribute_map"): - constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] - try: - for attr, mapconfig in data._attribute_map.items(): - if attr in constants: - continue - value = getattr(data, attr) - if value is None: - continue - local_type = mapconfig["type"] - internal_data_type = local_type.strip("[]{}") - if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): - continue - setattr(data, attr, self._deserialize(local_type, value)) - return data - except AttributeError: - return - - response, class_name = self._classify_target(target_obj, data) - - if isinstance(response, basestring): - return self.deserialize_data(data, response) - elif isinstance(response, type) and issubclass(response, Enum): - return self.deserialize_enum(data, response) - - if data is None: - return data - try: - attributes = response._attribute_map - d_attrs = {} - for attr, attr_desc in attributes.items(): - # Check empty string. If it's not empty, someone has a real "additionalProperties"... - if attr == "additional_properties" and attr_desc["key"] == "": - continue - raw_value = None - # Enhance attr_desc with some dynamic data - attr_desc = attr_desc.copy() # Do a copy, do not change the real one - internal_data_type = attr_desc["type"].strip("[]{}") - if internal_data_type in self.dependencies: - attr_desc["internalType"] = self.dependencies[internal_data_type] - - for key_extractor in self.key_extractors: - found_value = key_extractor(attr, attr_desc, data) - if found_value is not None: - if raw_value is not None and raw_value != found_value: - msg = ( - "Ignoring extracted value '%s' from %s for key '%s'" - " (duplicate extraction, follow extractors order)" - ) - _LOGGER.warning(msg, found_value, key_extractor, attr) - continue - raw_value = found_value - - value = self.deserialize_data(raw_value, attr_desc["type"]) - d_attrs[attr] = value - except (AttributeError, TypeError, KeyError) as err: - msg = "Unable to deserialize to object: " + class_name - raise_with_traceback(DeserializationError, msg, err) - else: - additional_properties = self._build_additional_properties(attributes, data) - return self._instantiate_model(response, d_attrs, additional_properties) - - def _build_additional_properties(self, attribute_map, data): - if not self.additional_properties_detection: - return None - if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": - # Check empty string. If it's not empty, someone has a real "additionalProperties" - return None - if isinstance(data, ET.Element): - data = {el.tag: el.text for el in data} - - known_keys = { - _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) - for desc in attribute_map.values() - if desc["key"] != "" - } - present_keys = set(data.keys()) - missing_keys = present_keys - known_keys - return {key: data[key] for key in missing_keys} - - def _classify_target(self, target, data): - """Check to see whether the deserialization target object can - be classified into a subclass. - Once classification has been determined, initialize object. - - :param str target: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - """ - if target is None: - return None, None - - if isinstance(target, basestring): - try: - target = self.dependencies[target] - except KeyError: - return target, target - - try: - target = target._classify(data, self.dependencies) - except AttributeError: - pass # Target is not a Model, no classify - return target, target.__class__.__name__ - - def failsafe_deserialize(self, target_obj, data, content_type=None): - """Ignores any errors encountered in deserialization, - and falls back to not deserializing the object. Recommended - for use in error deserialization, as we want to return the - HttpResponseError to users, and not have them deal with - a deserialization error. - - :param str target_obj: The target object type to deserialize to. - :param str/dict data: The response data to deseralize. - :param str content_type: Swagger "produces" if available. - """ - try: - return self(target_obj, data, content_type=content_type) - except: - _LOGGER.warning( - "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True - ) - return None - - @staticmethod - def _unpack_content(raw_data, content_type=None): - """Extract the correct structure for deserialization. - - If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. - if we can't, raise. Your Pipeline should have a RawDeserializer. - - If not a pipeline response and raw_data is bytes or string, use content-type - to decode it. If no content-type, try JSON. - - If raw_data is something else, bypass all logic and return it directly. - - :param raw_data: Data to be processed. - :param content_type: How to parse if raw_data is a string/bytes. - :raises JSONDecodeError: If JSON is requested and parsing is impossible. - :raises UnicodeDecodeError: If bytes is not UTF8 - """ - # Assume this is enough to detect a Pipeline Response without importing it - context = getattr(raw_data, "context", {}) - if context: - if RawDeserializer.CONTEXT_NAME in context: - return context[RawDeserializer.CONTEXT_NAME] - raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") - - # Assume this is enough to recognize universal_http.ClientResponse without importing it - if hasattr(raw_data, "body"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) - - # Assume this enough to recognize requests.Response without importing it. - if hasattr(raw_data, "_content_consumed"): - return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) - - if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): - return RawDeserializer.deserialize_from_text(raw_data, content_type) - return raw_data - - def _instantiate_model(self, response, attrs, additional_properties=None): - """Instantiate a response model passing in deserialized args. - - :param response: The response model class. - :param d_attrs: The deserialized response attributes. - """ - if callable(response): - subtype = getattr(response, "_subtype_map", {}) - try: - readonly = [k for k, v in response._validation.items() if v.get("readonly")] - const = [k for k, v in response._validation.items() if v.get("constant")] - kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} - response_obj = response(**kwargs) - for attr in readonly: - setattr(response_obj, attr, attrs.get(attr)) - if additional_properties: - response_obj.additional_properties = additional_properties - return response_obj - except TypeError as err: - msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) - raise DeserializationError(msg + str(err)) - else: - try: - for attr, value in attrs.items(): - setattr(response, attr, value) - return response - except Exception as exp: - msg = "Unable to populate response model. " - msg += "Type: {}, Error: {}".format(type(response), exp) - raise DeserializationError(msg) - - def deserialize_data(self, data, data_type): - """Process data for deserialization according to data type. - - :param str data: The response string to be deserialized. - :param str data_type: The type to deserialize to. - :raises: DeserializationError if deserialization fails. - :return: Deserialized object. - """ - if data is None: - return data - - try: - if not data_type: - return data - if data_type in self.basic_types.values(): - return self.deserialize_basic(data, data_type) - if data_type in self.deserialize_type: - if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): - return data - - is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] - if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: - return None - data_val = self.deserialize_type[data_type](data) - return data_val - - iter_type = data_type[0] + data_type[-1] - if iter_type in self.deserialize_type: - return self.deserialize_type[iter_type](data, data_type[1:-1]) - - obj_type = self.dependencies[data_type] - if issubclass(obj_type, Enum): - if isinstance(data, ET.Element): - data = data.text - return self.deserialize_enum(data, obj_type) - - except (ValueError, TypeError, AttributeError) as err: - msg = "Unable to deserialize response data." - msg += " Data: {}, {}".format(data, data_type) - raise_with_traceback(DeserializationError, msg, err) - else: - return self._deserialize(obj_type, data) - - def deserialize_iter(self, attr, iter_type): - """Deserialize an iterable. - - :param list attr: Iterable to be deserialized. - :param str iter_type: The type of object in the iterable. - :rtype: list - """ - if attr is None: - return None - if isinstance(attr, ET.Element): # If I receive an element here, get the children - attr = list(attr) - if not isinstance(attr, (list, set)): - raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) - return [self.deserialize_data(a, iter_type) for a in attr] - - def deserialize_dict(self, attr, dict_type): - """Deserialize a dictionary. - - :param dict/list attr: Dictionary to be deserialized. Also accepts - a list of key, value pairs. - :param str dict_type: The object type of the items in the dictionary. - :rtype: dict - """ - if isinstance(attr, list): - return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} - - if isinstance(attr, ET.Element): - # Transform value into {"Key": "value"} - attr = {el.tag: el.text for el in attr} - return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} - - def deserialize_object(self, attr, **kwargs): - """Deserialize a generic object. - This will be handled as a dictionary. - - :param dict attr: Dictionary to be deserialized. - :rtype: dict - :raises: TypeError if non-builtin datatype encountered. - """ - if attr is None: - return None - if isinstance(attr, ET.Element): - # Do no recurse on XML, just return the tree as-is - return attr - if isinstance(attr, basestring): - return self.deserialize_basic(attr, "str") - obj_type = type(attr) - if obj_type in self.basic_types: - return self.deserialize_basic(attr, self.basic_types[obj_type]) - if obj_type is _long_type: - return self.deserialize_long(attr) - - if obj_type == dict: - deserialized = {} - for key, value in attr.items(): - try: - deserialized[key] = self.deserialize_object(value, **kwargs) - except ValueError: - deserialized[key] = None - return deserialized - - if obj_type == list: - deserialized = [] - for obj in attr: - try: - deserialized.append(self.deserialize_object(obj, **kwargs)) - except ValueError: - pass - return deserialized - - else: - error = "Cannot deserialize generic object with type: " - raise TypeError(error + str(obj_type)) - - def deserialize_basic(self, attr, data_type): - """Deserialize basic builtin data type from string. - Will attempt to convert to str, int, float and bool. - This function will also accept '1', '0', 'true' and 'false' as - valid bool values. - - :param str attr: response string to be deserialized. - :param str data_type: deserialization data type. - :rtype: str, int, float or bool - :raises: TypeError if string format is not valid. - """ - # If we're here, data is supposed to be a basic type. - # If it's still an XML node, take the text - if isinstance(attr, ET.Element): - attr = attr.text - if not attr: - if data_type == "str": - # None or '', node is empty string. - return "" - else: - # None or '', node with a strong type is None. - # Don't try to model "empty bool" or "empty int" - return None - - if data_type == "bool": - if attr in [True, False, 1, 0]: - return bool(attr) - elif isinstance(attr, basestring): - if attr.lower() in ["true", "1"]: - return True - elif attr.lower() in ["false", "0"]: - return False - raise TypeError("Invalid boolean value: {}".format(attr)) - - if data_type == "str": - return self.deserialize_unicode(attr) - return eval(data_type)(attr) - - @staticmethod - def deserialize_unicode(data): - """Preserve unicode objects in Python 2, otherwise return data - as a string. - - :param str data: response string to be deserialized. - :rtype: str or unicode - """ - # We might be here because we have an enum modeled as string, - # and we try to deserialize a partial dict with enum inside - if isinstance(data, Enum): - return data - - # Consider this is real string - try: - if isinstance(data, unicode): - return data - except NameError: - return str(data) - else: - return str(data) - - @staticmethod - def deserialize_enum(data, enum_obj): - """Deserialize string into enum object. - - If the string is not a valid enum value it will be returned as-is - and a warning will be logged. - - :param str data: Response string to be deserialized. If this value is - None or invalid it will be returned as-is. - :param Enum enum_obj: Enum object to deserialize to. - :rtype: Enum - """ - if isinstance(data, enum_obj) or data is None: - return data - if isinstance(data, Enum): - data = data.value - if isinstance(data, int): - # Workaround. We might consider remove it in the future. - # https://github.com/Azure/azure-rest-api-specs/issues/141 - try: - return list(enum_obj.__members__.values())[data] - except IndexError: - error = "{!r} is not a valid index for enum {!r}" - raise DeserializationError(error.format(data, enum_obj)) - try: - return enum_obj(str(data)) - except ValueError: - for enum_value in enum_obj: - if enum_value.value.lower() == str(data).lower(): - return enum_value - # We don't fail anymore for unknown value, we deserialize as a string - _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) - return Deserializer.deserialize_unicode(data) - - @staticmethod - def deserialize_bytearray(attr): - """Deserialize string into bytearray. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return bytearray(b64decode(attr)) - - @staticmethod - def deserialize_base64(attr): - """Deserialize base64 encoded string into string. - - :param str attr: response string to be deserialized. - :rtype: bytearray - :raises: TypeError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - padding = "=" * (3 - (len(attr) + 3) % 4) - attr = attr + padding - encoded = attr.replace("-", "+").replace("_", "/") - return b64decode(encoded) - - @staticmethod - def deserialize_decimal(attr): - """Deserialize string into Decimal object. - - :param str attr: response string to be deserialized. - :rtype: Decimal - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - return decimal.Decimal(attr) - except decimal.DecimalException as err: - msg = "Invalid decimal {}".format(attr) - raise_with_traceback(DeserializationError, msg, err) - - @staticmethod - def deserialize_long(attr): - """Deserialize string into long (Py2) or int (Py3). - - :param str attr: response string to be deserialized. - :rtype: long or int - :raises: ValueError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - return _long_type(attr) - - @staticmethod - def deserialize_duration(attr): - """Deserialize ISO-8601 formatted string into TimeDelta object. - - :param str attr: response string to be deserialized. - :rtype: TimeDelta - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - duration = isodate.parse_duration(attr) - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize duration object." - raise_with_traceback(DeserializationError, msg, err) - else: - return duration - - @staticmethod - def deserialize_date(attr): - """Deserialize ISO-8601 formatted string into Date object. - - :param str attr: response string to be deserialized. - :rtype: Date - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. - return isodate.parse_date(attr, defaultmonth=None, defaultday=None) - - @staticmethod - def deserialize_time(attr): - """Deserialize ISO-8601 formatted string into time object. - - :param str attr: response string to be deserialized. - :rtype: datetime.time - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - if re.search(r"[^\W\d_]", attr, re.I + re.U): - raise DeserializationError("Date must have only digits and -. Received: %s" % attr) - return isodate.parse_time(attr) - - @staticmethod - def deserialize_rfc(attr): - """Deserialize RFC-1123 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - 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)) - ) - if not date_obj.tzinfo: - date_obj = date_obj.astimezone(tz=TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to rfc datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_iso(attr): - """Deserialize ISO-8601 formatted string into Datetime object. - - :param str attr: response string to be deserialized. - :rtype: Datetime - :raises: DeserializationError if string format invalid. - """ - if isinstance(attr, ET.Element): - attr = attr.text - try: - attr = attr.upper() - match = Deserializer.valid_date.match(attr) - if not match: - raise ValueError("Invalid datetime string: " + attr) - - check_decimal = attr.split(".") - if len(check_decimal) > 1: - decimal_str = "" - for digit in check_decimal[1]: - if digit.isdigit(): - decimal_str += digit - else: - break - if len(decimal_str) > 6: - attr = attr.replace(decimal_str, decimal_str[0:6]) - - date_obj = isodate.parse_datetime(attr) - test_utc = date_obj.utctimetuple() - if test_utc.tm_year > 9999 or test_utc.tm_year < 1: - raise OverflowError("Hit max or min date") - except (ValueError, OverflowError, AttributeError) as err: - msg = "Cannot deserialize datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj - - @staticmethod - def deserialize_unix(attr): - """Serialize Datetime object into IntTime format. - This is represented as seconds. - - :param int attr: Object to be serialized. - :rtype: Datetime - :raises: DeserializationError if format invalid - """ - if isinstance(attr, ET.Element): - attr = int(attr.text) - try: - date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) - except ValueError as err: - msg = "Cannot deserialize to unix datetime object." - raise_with_traceback(DeserializationError, msg, err) - else: - return date_obj diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_vendor.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_vendor.py deleted file mode 100644 index 54f238858ed..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_vendor.py +++ /dev/null @@ -1,17 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - - -def _format_url_section(template, **kwargs): - components = template.split("/") - while components: - try: - return template.format(**kwargs) - except KeyError as key: - formatted_components = template.split("/") - components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] - template = "/".join(components) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_version.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_version.py deleted file mode 100644 index eae7c95b6fb..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/_version.py +++ /dev/null @@ -1,9 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -VERSION = "0.1.0" diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/__init__.py deleted file mode 100644 index 30e6499d8dc..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/__init__.py +++ /dev/null @@ -1,21 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._client import XMSErrorResponseExtensions - -try: - from ._patch import __all__ as _patch_all - from ._patch import * # type: ignore # pylint: disable=unused-wildcard-import -except ImportError: - _patch_all = [] -from ._patch import patch_sdk as _patch_sdk - -__all__ = ["XMSErrorResponseExtensions"] -__all__.extend([p for p in _patch_all if p not in __all__]) - -_patch_sdk() diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_client.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_client.py deleted file mode 100644 index 434c1dae1ab..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_client.py +++ /dev/null @@ -1,71 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from copy import deepcopy -from typing import Any, Awaitable, TYPE_CHECKING - -from azure.core import AsyncPipelineClient -from azure.core.rest import AsyncHttpResponse, HttpRequest - -from .._serialization import Deserializer, Serializer -from ._configuration import XMSErrorResponseExtensionsConfiguration - -if TYPE_CHECKING: - # pylint: disable=unused-import,ungrouped-imports - from typing import Dict - - -class XMSErrorResponseExtensions: # pylint: disable=client-accepts-api-version-keyword - """XMS Error Response Extensions. - - :keyword endpoint: Service URL. Default value is "http://localhost:3000". - :paramtype endpoint: str - """ - - def __init__(self, *, endpoint: str = "http://localhost:3000", **kwargs: Any) -> None: - self._config = XMSErrorResponseExtensionsConfiguration(**kwargs) - self._client = AsyncPipelineClient(base_url=endpoint, config=self._config, **kwargs) - - self._serialize = Serializer() - self._deserialize = Deserializer() - self._serialize.client_side_validation = False - - def send_request(self, request: HttpRequest, **kwargs: Any) -> Awaitable[AsyncHttpResponse]: - """Runs the network request through the client's chained policies. - - We have helper methods to create requests specific to this service in `xmserrorresponselowlevel.rest`. - Use these helper methods to create the request you pass to this method. - - >>> from xmserrorresponselowlevel.rest import pet - >>> request = pet.build_get_pet_by_id_request(pet_id, **kwargs) - - >>> response = await client.send_request(request) - - - For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request - - :param request: The network request you want to make. Required. - :type request: ~azure.core.rest.HttpRequest - :keyword bool stream: Whether the response payload will be streamed. Defaults to False. - :return: The response of your network call. Does not do error handling on your response. - :rtype: ~azure.core.rest.AsyncHttpResponse - """ - - request_copy = deepcopy(request) - request_copy.url = self._client.format_url(request_copy.url) - return self._client.send_request(request_copy, **kwargs) - - async def close(self) -> None: - await self._client.close() - - async def __aenter__(self) -> "XMSErrorResponseExtensions": - await self._client.__aenter__() - return self - - async def __aexit__(self, *exc_details) -> None: - await self._client.__aexit__(*exc_details) diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_configuration.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_configuration.py deleted file mode 100644 index 95f1b3c4181..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_configuration.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from typing import Any - -from azure.core.configuration import Configuration -from azure.core.pipeline import policies - -from .._version import VERSION - - -class XMSErrorResponseExtensionsConfiguration(Configuration): # pylint: disable=too-many-instance-attributes - """Configuration for XMSErrorResponseExtensions. - - Note that all parameters used to create this instance are saved as instance - attributes. - """ - - def __init__(self, **kwargs: Any) -> None: - super(XMSErrorResponseExtensionsConfiguration, self).__init__(**kwargs) - - kwargs.setdefault("sdk_moniker", "xmserrorresponseextensions/{}".format(VERSION)) - 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 policies.HttpLoggingPolicy(**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") diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_patch.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_patch.py deleted file mode 100644 index f7dd3251033..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/aio/_patch.py +++ /dev/null @@ -1,20 +0,0 @@ -# ------------------------------------ -# Copyright (c) Microsoft Corporation. -# Licensed under the MIT License. -# ------------------------------------ -"""Customize generated code here. - -Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize -""" -from typing import List - -__all__: List[str] = [] # Add all objects you want publicly available to users at this package level - - -def patch_sdk(): - """Do not remove from this file. - - `patch_sdk` is a last resort escape hatch that allows you to do customizations - you can't accomplish using the techniques described in - https://aka.ms/azsdk/python/dpcodegen/python/customize - """ diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/py.typed b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/py.typed deleted file mode 100644 index e5aff4f83af..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/py.typed +++ /dev/null @@ -1 +0,0 @@ -# Marker file for PEP 561. \ No newline at end of file diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/__init__.py deleted file mode 100644 index 0af9b28f660..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/__init__.py +++ /dev/null @@ -1,6 +0,0 @@ -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/pet/__init__.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/pet/__init__.py deleted file mode 100644 index 0186f6e9219..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/pet/__init__.py +++ /dev/null @@ -1,17 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- - -from ._request_builders import build_get_pet_by_id_request -from ._request_builders import build_do_something_request -from ._request_builders import build_has_models_param_request - -__all__ = [ - "build_get_pet_by_id_request", - "build_do_something_request", - "build_has_models_param_request", -] diff --git a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/pet/_request_builders.py b/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/pet/_request_builders.py deleted file mode 100644 index 44ccb98cb58..00000000000 --- a/test/vanilla/low-level/Expected/AcceptanceTests/XmsErrorResponseLowLevel/xmserrorresponselowlevel/rest/pet/_request_builders.py +++ /dev/null @@ -1,115 +0,0 @@ -# coding=utf-8 -# -------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# Code generated by Microsoft (R) AutoRest Code Generator. -# Changes may cause incorrect behavior and will be lost if the code is regenerated. -# -------------------------------------------------------------------------- -from typing import Any - -from azure.core.rest import HttpRequest -from azure.core.utils import case_insensitive_dict - -from ..._serialization import Serializer -from ..._vendor import _format_url_section - -_SERIALIZER = Serializer() -_SERIALIZER.client_side_validation = False - - -def build_get_pet_by_id_request(pet_id: str, **kwargs: Any) -> HttpRequest: - """Gets pets by id. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param pet_id: pet id. Required. - :type pet_id: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/errorStatusCodes/Pets/{petId}/GetPet" - path_format_arguments = { - "petId": _SERIALIZER.url("pet_id", pet_id, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="GET", url=_url, headers=_headers, **kwargs) - - -def build_do_something_request(what_action: str, **kwargs: Any) -> HttpRequest: - """Asks pet to do something. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :param what_action: what action the pet should do. Required. - :type what_action: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/errorStatusCodes/Pets/doSomething/{whatAction}" - path_format_arguments = { - "whatAction": _SERIALIZER.url("what_action", what_action, "str"), - } - - _url = _format_url_section(_url, **path_format_arguments) - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, headers=_headers, **kwargs) - - -def build_has_models_param_request(*, models: str = "value1", **kwargs: Any) -> HttpRequest: - """Ensure you can correctly deserialize the returned PetActionError and deserialization doesn't - conflict with the input param name 'models'. - - See https://aka.ms/azsdk/dpcodegen/python/send_request for how to incorporate this request - builder into your code flow. - - :keyword models: Make sure model deserialization doesn't conflict with this param name, which - has input name 'models'. Use client default value in call. Default value is "value1". - :paramtype models: str - :return: Returns an :class:`~azure.core.rest.HttpRequest` that you will pass to the client's - `send_request` method. See https://aka.ms/azsdk/dpcodegen/python/send_request for how to - incorporate this response into your code flow. - :rtype: ~azure.core.rest.HttpRequest - """ - - _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) - _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) - - accept = _headers.pop("Accept", "application/json") - - # Construct URL - _url = "/errorStatusCodes/Pets/hasModelsParam" - - # Construct parameters - if models is not None: - _params["models"] = _SERIALIZER.query("models", models, "str") - - # Construct headers - _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") - - return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) diff --git a/test/vanilla/low-level/coverage/report-optional.json b/test/vanilla/low-level/coverage/report-optional.json deleted file mode 100644 index b5703774a0f..00000000000 --- a/test/vanilla/low-level/coverage/report-optional.json +++ /dev/null @@ -1,50 +0,0 @@ -{ - "StreamUploadFile": 10, - "UpdatePetWithForm": 2, - "UrlEncodedDataWithPartialConstantBody": 0, - "getDecimalInvalid": 2, - "getDecimalBig": 2, - "getDecimalSmall": 2, - "getDecimalBigPositiveDecimal": 2, - "getDecimalBigNegativeDecimal": 2, - "putDecimalBig": 2, - "putDecimalSmall": 2, - "putDecimalBigPositiveDecimal": 2, - "putDecimalBigNegativeDecimal": 0, - "putDateTimeMaxUtc7MS": 0, - "getDateTimeMaxUtc7MSUppercase": 2, - "putDateTimeMaxLocalPositiveOffset": 2, - "putDateTimeMaxLocalNegativeOffset": 0, - "putDateTimeMinLocalPositiveOffset": 0, - "putDateTimeMinLocalNegativeOffset": 2, - "HeaderParameterProtectedKey": 1, - "CustomHeaderInRequest": 2, - "FormdataStreamUploadFile": 4, - "HttpSuccess200Options": 0, - "HttpRedirect307Options": 0, - "HttpRetry502Options": 0, - "HttpClientFailure400Options": 0, - "HttpClientFailure403Options": 0, - "HttpClientFailure412Options": 0, - "ResponsesScenarioNoModelEmptyBody": 2, - "sendErrorWithParamNameModels": 0, - "MultiapiPutTestOneApiVersionOne": 0, - "MultiapiPutTestOneApiVersionTwo": 0, - "MultiapiGetTestTwoApiVersionOne": 0, - "MultiapiGetTestTwoApiVersionTwo": 0, - "MultiapiGetTestTwoApiVersionThree": 0, - "MultiapiPutTestThreeApiVersionTwo": 0, - "MultiapiPostTestFourApiVersionTwo": 0, - "MultiapiPostTestFourApiVersionThreeJSON": 0, - "MultiapiPostTestFourApiVersionThreePDF": 0, - "MultiapiPutTestFiveApiVersionThree": 0, - "MultiapiLRO": 0, - "MultiapiPaging": 0, - "MultiapiLROAndPaging": 0, - "MultiapiDifferentCallsApiVersionOne": 0, - "MultiapiDifferentCallsApiVersionTwo": 0, - "MultiapiDifferentCallsApiVersionThree": 0, - "MultiapiCustomBaseUrlApiVersionOne": 0, - "MultiapiCustomBaseUrlApiVersionTwo": 0, - "LROPatchInlineCompleteIgnoreHeaders": 0 -} \ No newline at end of file diff --git a/test/vanilla/low-level/coverage/report-vanilla.json b/test/vanilla/low-level/coverage/report-vanilla.json deleted file mode 100644 index 0e90f70df05..00000000000 --- a/test/vanilla/low-level/coverage/report-vanilla.json +++ /dev/null @@ -1,627 +0,0 @@ -{ - "additionalPropertiesTrue": 0, - "additionalPropertiesSubclass": 0, - "additionalPropertiesTypeObject": 0, - "additionalPropertiesTypeString": 0, - "additionalPropertiesInProperties": 0, - "additionalPropertiesInPropertiesWithAPTypeString": 0, - "GetStringAsAnything": 0, - "PutStringAsAnything": 0, - "GetObjectAsAnything": 0, - "PutObjectAsAnything": 0, - "GetArrayAsAnything": 0, - "PutArrayAsAnything": 0, - "putArrayEmpty": 0, - "getArrayEmpty": 0, - "getArrayNull": 0, - "getArrayInvalid": 0, - "getArrayBooleanValid": 0, - "putArrayBooleanValid": 0, - "getArrayBooleanWithNull": 0, - "getArrayBooleanWithString": 0, - "getArrayIntegerValid": 0, - "putArrayIntegerValid": 0, - "getArrayIntegerWithNull": 0, - "getArrayIntegerWithString": 0, - "getArrayLongValid": 0, - "putArrayLongValid": 0, - "getArrayLongWithNull": 0, - "getArrayLongWithString": 0, - "getArrayFloatValid": 0, - "putArrayFloatValid": 0, - "getArrayFloatWithNull": 0, - "getArrayFloatWithString": 0, - "getArrayDoubleValid": 0, - "putArrayDoubleValid": 0, - "getArrayDoubleWithNull": 0, - "getArrayDoubleWithString": 0, - "getArrayStringValid": 0, - "putArrayStringValid": 0, - "getArrayStringWithNull": 0, - "getArrayStringWithNumber": 0, - "getArrayEnumValid": 0, - "putArrayEnumValid": 0, - "getArrayStringEnumValid": 0, - "putArrayStringEnumValid": 0, - "getArrayUuidValid": 0, - "putArrayUuidValid": 0, - "getArrayUuidWithInvalidChars": 0, - "getArrayDateValid": 0, - "putArrayDateValid": 0, - "getArrayDateWithNull": 0, - "getArrayDateWithInvalidChars": 0, - "getArrayDateTimeValid": 0, - "putArrayDateTimeValid": 0, - "getArrayDateTimeWithNull": 0, - "getArrayDateTimeWithInvalidChars": 0, - "getArrayDateTimeRfc1123Valid": 0, - "getDateTimeRfc1123Valid": 0, - "getArrayDurationValid": 0, - "putArrayDurationValid": 0, - "getArrayByteValid": 0, - "putArrayByteValid": 0, - "getArrayByteWithNull": 0, - "getArrayBase64Url": 0, - "getArrayComplexNull": 0, - "getArrayComplexEmpty": 0, - "getArrayComplexItemNull": 0, - "getArrayComplexItemEmpty": 0, - "getArrayComplexValid": 0, - "putArrayComplexValid": 0, - "getArrayArrayNull": 0, - "getArrayArrayEmpty": 0, - "getArrayArrayItemNull": 0, - "getArrayArrayItemEmpty": 0, - "getArrayArrayValid": 0, - "putArrayArrayValid": 0, - "getArrayDictionaryNull": 0, - "getArrayDictionaryEmpty": 0, - "getArrayDictionaryItemNull": 0, - "getArrayDictionaryItemEmpty": 0, - "getArrayDictionaryValid": 0, - "putArrayDictionaryValid": 0, - "BodyBinaryFile": 0, - "BodyBinaryOctet": 0, - "getBoolTrue": 0, - "putBoolTrue": 0, - "getBoolFalse": 0, - "putBoolFalse": 0, - "getBoolNull": 0, - "getBoolInvalid": 0, - "putByteNonAscii": 0, - "getByteNull": 0, - "getByteEmpty": 0, - "getByteNonAscii": 0, - "getByteInvalid": 0, - "ConstantClientProperties": 0, - "ErrorWithSecrets": 0, - "RequestWithSecrets": 0, - "HttpSuccess200Head": 0, - "HttpSuccess200Get": 0, - "HttpSuccess200Put": 0, - "HttpSuccess200Post": 0, - "HttpSuccess200Patch": 0, - "HttpSuccess200Delete": 0, - "HttpSuccess201Put": 0, - "HttpSuccess201Post": 0, - "HttpSuccess202Put": 0, - "HttpSuccess202Post": 0, - "HttpSuccess202Patch": 0, - "HttpSuccess202Delete": 0, - "HttpSuccess204Head": 0, - "HttpSuccess204Put": 0, - "HttpSuccess204Post": 0, - "HttpSuccess204Patch": 0, - "HttpSuccess204Delete": 0, - "HttpSuccess404Head": 0, - "HttpRedirect300Head": 0, - "HttpRedirect300Get": 0, - "HttpRedirect301Head": 0, - "HttpRedirect301Put": 0, - "HttpRedirect301Get": 0, - "HttpRedirect302Head": 0, - "HttpRedirect302Get": 0, - "HttpRedirect302Patch": 0, - "HttpRedirect303Post": 0, - "HttpRedirect307Head": 0, - "HttpRedirect307Get": 0, - "HttpRedirect307Put": 0, - "HttpRedirect307Post": 0, - "HttpRedirect307Patch": 0, - "HttpRedirect307Delete": 0, - "HttpRedirect307Options": 0, - "HttpClientFailure400Head": 0, - "HttpClientFailure400Get": 0, - "HttpClientFailure400Put": 0, - "HttpClientFailure400Post": 0, - "HttpClientFailure400Patch": 0, - "HttpClientFailure400Delete": 0, - "HttpClientFailure401Head": 0, - "HttpClientFailure402Get": 0, - "HttpClientFailure403Get": 0, - "HttpClientFailure404Put": 0, - "HttpClientFailure405Patch": 0, - "HttpClientFailure406Post": 0, - "HttpClientFailure407Delete": 0, - "HttpClientFailure409Put": 0, - "HttpClientFailure410Head": 0, - "HttpClientFailure411Get": 0, - "HttpClientFailure412Get": 0, - "HttpClientFailure413Put": 0, - "HttpClientFailure414Patch": 0, - "HttpClientFailure415Post": 0, - "HttpClientFailure416Get": 0, - "HttpClientFailure417Delete": 0, - "HttpClientFailure429Head": 0, - "HttpServerFailure501Head": 0, - "HttpServerFailure501Get": 0, - "HttpServerFailure505Post": 0, - "HttpServerFailure505Delete": 0, - "HttpRetry408Head": 0, - "HttpRetry500Put": 0, - "HttpRetry500Patch": 0, - "HttpRetry502Get": 0, - "HttpRetry503Post": 0, - "HttpRetry503Delete": 0, - "HttpRetry504Put": 0, - "HttpRetry504Patch": 0, - "ResponsesScenarioA200MatchingModel": 0, - "ResponsesScenarioA201DefaultNoModel": 0, - "ResponsesScenarioA202DefaultNoModel": 0, - "ResponsesScenarioA204MatchingNoModel": 0, - "ResponsesScenarioA400DefaultModel": 0, - "ResponsesScenarioB200MatchingModel": 0, - "ResponsesScenarioB201MatchingModel": 0, - "ResponsesScenarioB400DefaultModel": 0, - "ResponsesScenarioC200MatchingModel": 0, - "ResponsesScenarioC201MatchingModel": 0, - "ResponsesScenarioC404MatchingModel": 0, - "ResponsesScenarioC400DefaultModel": 0, - "ResponsesScenarioD202MatchingNoModel": 0, - "ResponsesScenarioD204MatchingNoModel": 0, - "ResponsesScenarioD400DefaultModel": 0, - "ResponsesScenarioE202MatchingInvalid": 0, - "ResponsesScenarioE204MatchingNoModel": 0, - "ResponsesScenarioE400DefaultNoModel": 0, - "ResponsesScenarioE400DefaultInvalid": 0, - "ResponsesScenarioF200DefaultModel": 0, - "ResponsesScenarioF200DefaultNone": 0, - "ResponsesScenarioF400DefaultModel": 0, - "ResponsesScenarioF400DefaultNone": 0, - "ResponsesScenarioG200DefaultInvalid": 0, - "ResponsesScenarioG200DefaultNoModel": 0, - "ResponsesScenarioG400DefaultInvalid": 0, - "ResponsesScenarioG400DefaultNoModel": 0, - "ResponsesScenarioH200MatchingNone": 0, - "ResponsesScenarioH200MatchingModel": 0, - "ResponsesScenarioH200MatchingInvalid": 0, - "ResponsesScenarioH400NonMatchingNone": 0, - "ResponsesScenarioH400NonMatchingModel": 0, - "ResponsesScenarioH400NonMatchingInvalid": 0, - "ResponsesScenarioH202NonMatchingModel": 0, - "ResponsesScenarioEmptyErrorBody": 0, - "ResponsesScenarioNoModelErrorBody": 0, - "ResponsesScenarioNoModelEmptyBody": 0, - "verifyIncorrectErrorParsing": 0, - "MediaTypesAnalyzeBodyNoAcceptHeader": 0, - "MediaTypesTwoContentTypes": 0, - "MediaTypesThreeContentTypes": 0, - "PassMergePatchObject": 0, - "GetParameterizedHostWithNameEndpoint": 0, - "UrlPathsBoolTrue": 0, - "UrlPathsBoolFalse": 0, - "UrlPathsIntPositive": 0, - "UrlPathsIntUnixTime": 0, - "UrlPathsIntNegative": 0, - "UrlPathsLongPositive": 0, - "UrlPathsLongNegative": 0, - "UrlPathsFloatPositive": 0, - "UrlPathsFloatNegative": 0, - "UrlPathsDoublePositive": 0, - "UrlPathsDoubleNegative": 0, - "UrlPathsStringEmpty": 0, - "UrlPathsStringUnicode": 0, - "UrlPathsStringUrlEncoded": 0, - "UrlPathsStringUrlNonEncoded": 0, - "UrlPathsStringBase64Url": 0, - "UrlPathsByteEmpty": 0, - "UrlPathsByteMultiByte": 0, - "UrlPathsDateValid": 0, - "UrlPathsDateTimeValid": 0, - "UrlPathsEnumValid": 0, - "UrlPathsArrayCSVInPath": 0, - "ImplicitOptionalBinaryBody": 0, - "ExplicitOptionalBinaryBody": 0, - "ExplicitRequiredBinaryBody": 0, - "OptionalImplicitBody": 0, - "GeneralOptional": 0, - "OptionalImplicitHeader": 0, - "OptionalImplicitQuery": 0, - "OptionalGlobalQuery": 0, - "reservedWordsOperationGroupImport": 1, - "reservedWordsBodyNamedContent": 0, - "reservedWordsBodyNamedJson": 1, - "reservedWordsBodyNamedData": 1, - "reservedWordsBodyNamedFiles": 1, - "reservedWordsUrlHeaderQuery": 0, - "SecurityKey": 4, - "SecurityAad": 4, - "getStringNull": 0, - "putStringNull": 0, - "getStringEmpty": 0, - "putStringEmpty": 0, - "getStringNotProvided": 0, - "getStringWithLeadingAndTrailingWhitespace": 0, - "putStringWithLeadingAndTrailingWhitespace": 0, - "getStringBase64UrlEncoded": 0, - "putStringBase64UrlEncoded": 0, - "getStringBase64Encoded": 0, - "getStringNullBase64UrlEncoding": 0, - "getStringMultiByteCharacters": 0, - "putStringMultiByteCharacters": 0, - "getEnumNotExpandable": 0, - "putEnumNotExpandable": 0, - "getEnumReferenced": 0, - "putEnumReferenced": 0, - "getEnumReferencedConstant": 0, - "putEnumReferencedConstant": 0, - "XmlGetBytes": 0, - "XmlPutBytes": 0, - "XmlGetUrl": 0, - "XmlPutUrl": 0, - "verifyHost": 0, - "putArrayDateTimeRfc1123Valid": 0, - "getDateNull": 0, - "getDateInvalid": 0, - "getDateOverflow": 0, - "getDateUnderflow": 0, - "getDateMax": 0, - "putDateMax": 0, - "getDateMin": 0, - "putDateMin": 0, - "getDateTimeNull": 0, - "getDateTimeInvalid": 0, - "getDateTimeOverflow": 0, - "getDateTimeUnderflow": 0, - "putDateTimeMaxUtc": 0, - "getDateTimeMaxUtcLowercase": 0, - "getDateTimeMaxUtcUppercase": 0, - "getDateTimeMaxLocalPositiveOffsetLowercase": 0, - "getDateTimeMaxLocalPositiveOffsetUppercase": 0, - "getDateTimeMaxLocalNegativeOffsetLowercase": 0, - "getDateTimeMaxLocalNegativeOffsetUppercase": 0, - "getDateTimeMinUtc": 0, - "putDateTimeMinUtc": 0, - "getDateTimeMinLocalPositiveOffset": 0, - "getDateTimeMinLocalNegativeOffset": 0, - "getDateTimeRfc1123Null": 0, - "getDateTimeRfc1123Invalid": 0, - "getDateTimeRfc1123Overflow": 0, - "getDateTimeRfc1123Underflow": 0, - "getDateTimeRfc1123MinUtc": 0, - "putDateTimeRfc1123Max": 0, - "putDateTimeRfc1123Min": 0, - "getDateTimeRfc1123MaxUtcLowercase": 0, - "getDateTimeRfc1123MaxUtcUppercase": 0, - "getIntegerNull": 0, - "getIntegerInvalid": 0, - "getIntegerOverflow": 0, - "getIntegerUnderflow": 0, - "getLongOverflow": 0, - "getLongUnderflow": 0, - "putIntegerMax": 0, - "putLongMax": 0, - "putIntegerMin": 0, - "putLongMin": 0, - "getNumberNull": 0, - "getFloatInvalid": 0, - "getDoubleInvalid": 0, - "getFloatBigScientificNotation": 0, - "putFloatBigScientificNotation": 0, - "getDoubleBigScientificNotation": 0, - "putDoubleBigScientificNotation": 0, - "getDoubleBigPositiveDecimal": 0, - "putDoubleBigPositiveDecimal": 0, - "getDoubleBigNegativeDecimal": 0, - "putDoubleBigNegativeDecimal": 0, - "getFloatSmallScientificNotation": 0, - "putFloatSmallScientificNotation": 0, - "getDoubleSmallScientificNotation": 0, - "putDoubleSmallScientificNotation": 0, - "putComplexBasicValid": 0, - "getComplexBasicValid": 0, - "getComplexBasicEmpty": 0, - "getComplexBasicNotProvided": 0, - "getComplexBasicNull": 0, - "getComplexBasicInvalid": 0, - "putComplexPrimitiveInteger": 0, - "putComplexPrimitiveLong": 0, - "putComplexPrimitiveFloat": 0, - "putComplexPrimitiveDouble": 0, - "putComplexPrimitiveBool": 0, - "putComplexPrimitiveString": 0, - "putComplexPrimitiveDate": 0, - "putComplexPrimitiveDateTime": 0, - "putComplexPrimitiveDateTimeRfc1123": 0, - "putComplexPrimitiveDuration": 0, - "putComplexPrimitiveByte": 0, - "getComplexPrimitiveInteger": 0, - "getComplexPrimitiveLong": 0, - "getComplexPrimitiveFloat": 0, - "getComplexPrimitiveDouble": 0, - "getComplexPrimitiveBool": 0, - "getComplexPrimitiveString": 0, - "getComplexPrimitiveDate": 0, - "getComplexPrimitiveDateTime": 0, - "getComplexPrimitiveDateTimeRfc1123": 0, - "getComplexPrimitiveDuration": 0, - "getComplexPrimitiveByte": 0, - "putComplexArrayValid": 0, - "putComplexArrayEmpty": 0, - "getComplexArrayValid": 0, - "getComplexArrayEmpty": 0, - "getComplexArrayNotProvided": 0, - "putComplexDictionaryValid": 0, - "putComplexDictionaryEmpty": 0, - "getComplexDictionaryValid": 0, - "getComplexDictionaryEmpty": 0, - "getComplexDictionaryNull": 0, - "getComplexDictionaryNotProvided": 0, - "putComplexInheritanceValid": 0, - "getComplexInheritanceValid": 0, - "putComplexPolymorphismValid": 0, - "getComplexPolymorphismValid": 0, - "putComplexPolymorphismComplicated": 0, - "getComplexPolymorphismComplicated": 0, - "putComplexPolymorphismNoDiscriminator": 0, - "putComplexPolymorphicRecursiveValid": 0, - "getComplexPolymorphicRecursiveValid": 0, - "putComplexReadOnlyPropertyValid": 0, - "getComplexReadOnlyPropertyValid": 0, - "UrlQueriesBoolFalse": 0, - "UrlQueriesBoolTrue": 0, - "UrlQueriesBoolNull": 0, - "UrlQueriesIntPositive": 0, - "UrlQueriesIntNegative": 0, - "UrlQueriesIntNull": 0, - "UrlQueriesLongPositive": 0, - "UrlQueriesLongNegative": 0, - "UrlQueriesLongNull": 0, - "UrlQueriesFloatPositive": 0, - "UrlQueriesFloatNegative": 0, - "UrlQueriesFloatNull": 0, - "UrlQueriesDoublePositive": 0, - "UrlQueriesDoubleNegative": 0, - "UrlQueriesDoubleNull": 0, - "UrlQueriesStringUrlEncoded": 0, - "UrlQueriesStringEmpty": 0, - "UrlQueriesStringNull": 0, - "UrlQueriesStringUnicode": 0, - "UrlQueriesEnumValid": 0, - "UrlQueriesEnumNull": 0, - "UrlQueriesByteMultiByte": 0, - "UrlQueriesByteEmpty": 0, - "UrlQueriesByteNull": 0, - "UrlQueriesDateValid": 0, - "UrlQueriesDateNull": 0, - "UrlQueriesDateTimeValid": 0, - "UrlQueriesDateTimeNull": 0, - "UrlQueriesArrayCsvNull": 0, - "UrlQueriesArrayCsvEmpty": 0, - "UrlQueriesArrayCsvValid": 0, - "UrlQueriesArrayMultiNull": 0, - "UrlQueriesArrayMultiEmpty": 0, - "UrlQueriesArrayMultiValid": 0, - "UrlQueriesArraySsvValid": 0, - "UrlQueriesArrayPipesValid": 0, - "UrlQueriesArrayTsvValid": 0, - "UrlQueriesArrayNoCollectionFormatValid": 0, - "UrlPathItemGetAll": 0, - "UrlPathItemGetGlobalNull": 0, - "UrlPathItemGetGlobalAndLocalNull": 0, - "UrlPathItemGetPathItemAndLocalNull": 0, - "putDictionaryEmpty": 0, - "getDictionaryNull": 0, - "getDictionaryEmpty": 0, - "getDictionaryInvalid": 0, - "getDictionaryNullValue": 0, - "getDictionaryNullkey": 0, - "getDictionaryKeyEmptyString": 0, - "getDictionaryBooleanValid": 0, - "getDictionaryBooleanWithNull": 0, - "getDictionaryBooleanWithString": 0, - "getDictionaryIntegerValid": 0, - "getDictionaryIntegerWithNull": 0, - "getDictionaryIntegerWithString": 0, - "getDictionaryLongValid": 0, - "getDictionaryLongWithNull": 0, - "getDictionaryLongWithString": 0, - "getDictionaryFloatValid": 0, - "getDictionaryFloatWithNull": 0, - "getDictionaryFloatWithString": 0, - "getDictionaryDoubleValid": 0, - "getDictionaryDoubleWithNull": 0, - "getDictionaryDoubleWithString": 0, - "getDictionaryStringValid": 0, - "getDictionaryStringWithNull": 0, - "getDictionaryStringWithNumber": 0, - "getDictionaryDateValid": 0, - "getDictionaryDateWithNull": 0, - "getDictionaryDateWithInvalidChars": 0, - "getDictionaryDateTimeValid": 0, - "getDictionaryDateTimeWithNull": 0, - "getDictionaryDateTimeWithInvalidChars": 0, - "getDictionaryDateTimeRfc1123Valid": 0, - "getDictionaryDurationValid": 0, - "getDictionaryByteValid": 0, - "getDictionaryByteWithNull": 0, - "putDictionaryBooleanValid": 0, - "putDictionaryIntegerValid": 0, - "putDictionaryLongValid": 0, - "putDictionaryFloatValid": 0, - "putDictionaryDoubleValid": 0, - "putDictionaryStringValid": 0, - "putDictionaryDateValid": 0, - "putDictionaryDateTimeValid": 0, - "putDictionaryDateTimeRfc1123Valid": 0, - "putDictionaryDurationValid": 0, - "putDictionaryByteValid": 0, - "getDictionaryComplexNull": 0, - "getDictionaryComplexEmpty": 0, - "getDictionaryComplexItemNull": 0, - "getDictionaryComplexItemEmpty": 0, - "getDictionaryComplexValid": 0, - "putDictionaryComplexValid": 0, - "getDictionaryArrayNull": 0, - "getDictionaryArrayEmpty": 0, - "getDictionaryArrayItemNull": 0, - "getDictionaryArrayItemEmpty": 0, - "getDictionaryArrayValid": 0, - "putDictionaryArrayValid": 0, - "getDictionaryDictionaryNull": 0, - "getDictionaryDictionaryEmpty": 0, - "getDictionaryDictionaryItemNull": 0, - "getDictionaryDictionaryItemEmpty": 0, - "getDictionaryDictionaryValid": 0, - "putDictionaryDictionaryValid": 0, - "putDurationPositive": 0, - "getDurationNull": 0, - "getDurationInvalid": 0, - "getDurationPositive": 0, - "HeaderParameterExistingKey": 0, - "HeaderResponseExistingKey": 0, - "HeaderResponseProtectedKey": 0, - "HeaderParameterIntegerPositive": 0, - "HeaderParameterIntegerNegative": 0, - "HeaderParameterLongPositive": 0, - "HeaderParameterLongNegative": 0, - "HeaderParameterFloatPositive": 0, - "HeaderParameterFloatNegative": 0, - "HeaderParameterDoublePositive": 0, - "HeaderParameterDoubleNegative": 0, - "HeaderParameterBoolTrue": 0, - "HeaderParameterBoolFalse": 0, - "HeaderParameterStringValid": 0, - "HeaderParameterStringNull": 0, - "HeaderParameterStringEmpty": 0, - "HeaderParameterDateValid": 0, - "HeaderParameterDateMin": 0, - "HeaderParameterDateTimeValid": 0, - "HeaderParameterDateTimeMin": 0, - "HeaderParameterDateTimeRfc1123Valid": 0, - "HeaderParameterDateTimeRfc1123Min": 0, - "HeaderParameterBytesValid": 0, - "HeaderParameterDurationValid": 0, - "HeaderResponseIntegerPositive": 0, - "HeaderResponseIntegerNegative": 0, - "HeaderResponseLongPositive": 0, - "HeaderResponseLongNegative": 0, - "HeaderResponseFloatPositive": 0, - "HeaderResponseFloatNegative": 0, - "HeaderResponseDoublePositive": 0, - "HeaderResponseDoubleNegative": 0, - "HeaderResponseBoolTrue": 0, - "HeaderResponseBoolFalse": 0, - "HeaderResponseStringValid": 0, - "HeaderResponseStringNull": 0, - "HeaderResponseStringEmpty": 0, - "HeaderParameterEnumValid": 0, - "HeaderParameterEnumNull": 0, - "HeaderResponseEnumValid": 0, - "HeaderResponseEnumNull": 0, - "HeaderResponseDateValid": 0, - "HeaderResponseDateMin": 0, - "HeaderResponseDateTimeValid": 0, - "HeaderResponseDateTimeMin": 0, - "HeaderResponseDateTimeRfc1123Valid": 0, - "HeaderResponseDateTimeRfc1123Min": 0, - "HeaderResponseBytesValid": 0, - "HeaderResponseDurationValid": 0, - "ConstantsInPath": 0, - "ConstantsInBody": 0, - "CustomBaseUri": 0, - "CustomBaseUriMoreOptions": 0, - "getModelFlattenArray": 0, - "putModelFlattenArray": 0, - "getModelFlattenDictionary": 0, - "putModelFlattenDictionary": 0, - "getModelFlattenResourceCollection": 0, - "putModelFlattenResourceCollection": 0, - "putModelFlattenCustomBase": 0, - "postModelFlattenCustomParameter": 0, - "putModelFlattenCustomGroupedParameter": 0, - "getDictionaryBase64Url": 0, - "getUnixTime": 0, - "getInvalidUnixTime": 0, - "getNullUnixTime": 0, - "putUnixTime": 0, - "expectedEnum": 0, - "unexpectedEnum": 0, - "allowedValueEnum": 0, - "roundTripEnum": 0, - "expectedNoErrors": 0, - "expectedPetSadError": 0, - "expectedPetHungryError": 0, - "intError": 0, - "stringError": 0, - "animalNotFoundError": 0, - "linkNotFoundError": 0, - "getDateTimeMinLocalNoOffset": 0, - "getComplexPolymorphismDotSyntax": 0, - "getComposedWithDiscriminator": 0, - "getComposedWithoutDiscriminator": 0, - "FileStreamNonempty": 0, - "FileStreamVeryLarge": 0, - "FileStreamEmpty": 0, - "MediaTypeJson": 0, - "MediaTypePdf": 0, - "MediaTypeWithEncoding": 0, - "StorageListContainersXML": 0, - "StorageGetServicePropertiesXML": 0, - "StoragePutServicePropertiesXML": 0, - "StorageGetContainerACLXML": 0, - "StorageListBlobsXML": 0, - "StoragePutContainerACLXML": 0, - "GetSimpleXML": 0, - "PutSimpleXML": 0, - "GetWrappedXMLList": 0, - "PutWrappedXMLList": 0, - "GetEmptyXMLList": 0, - "PutEmptyXMLList": 0, - "GetEmptyWrappedXMLList": 0, - "PutEmptyWrappedXMLList": 0, - "GetXMLListAtRoot": 0, - "PutXMLListAtRoot": 0, - "GetXMLListAtRootSingle": 0, - "PutXMLListAtRootSingle": 0, - "GetEmptyXMLListAtRoot": 0, - "PutEmptyXMLListAtRoot": 0, - "GetXMLEmptyNode": 0, - "PutXMLEmptyNode": 0, - "GetRootWithRefAndNoMetaXML": 0, - "PutRootWithRefAndNoMetaXML": 0, - "GetRootWithRefAndMetaXML": 0, - "PutRootWithRefAndMetaXML": 0, - "jsonInputInXMLSwagger": 0, - "jsonOutputInXMLSwagger": 0, - "GetWithXMsText": 0, - "ObjectTypeResponse": 0, - "ObjectTypePut": 0, - "ObjectTypeErrorResponse": 0, - "NonStringEnumsPostInt": 0, - "NonStringEnumsGetInt": 0, - "NonStringEnumsPostFloat": 0, - "NonStringEnumsGetFloat": 0, - "BodyTimeGet": 0, - "BodyTimePut": 0, - "MultipleInheritancePetGet": 0, - "MultipleInheritancePetPut": 0, - "MultipleInheritanceHorseGet": 0, - "MultipleInheritanceHorsePut": 0, - "MultipleInheritanceFelineGet": 0, - "MultipleInheritanceFelinePut": 0, - "MultipleInheritanceCatGet": 0, - "MultipleInheritanceCatPut": 0, - "MultipleInheritanceKittenGet": 0, - "MultipleInheritanceKittenPut": 0 -} \ No newline at end of file diff --git a/test/vanilla/low-level/requirements.txt b/test/vanilla/low-level/requirements.txt deleted file mode 100644 index fd6b444b4eb..00000000000 --- a/test/vanilla/low-level/requirements.txt +++ /dev/null @@ -1,53 +0,0 @@ -aiohttp;python_full_version>="3.5.2" -requests==2.20.0 -pytest -pytest-cov -pytest-asyncio==0.14.0;python_full_version>="3.5.2" -async_generator;python_full_version>="3.5.2" -azure-core==1.24.0 --e ./Expected/AcceptanceTests/AdditionalPropertiesLowLevel --e ./Expected/AcceptanceTests/AnythingLowLevel --e ./Expected/AcceptanceTests/BodyArrayLowLevel --e ./Expected/AcceptanceTests/BodyBinaryLowLevel --e ./Expected/AcceptanceTests/BodyBooleanLowLevel --e ./Expected/AcceptanceTests/BodyByteLowLevel --e ./Expected/AcceptanceTests/BodyComplexLowLevel --e ./Expected/AcceptanceTests/BodyDateLowLevel --e ./Expected/AcceptanceTests/BodyDateTimeLowLevel --e ./Expected/AcceptanceTests/BodyDateTimeRfc1123LowLevel --e ./Expected/AcceptanceTests/BodyDictionaryLowLevel --e ./Expected/AcceptanceTests/BodyDurationLowLevel --e ./Expected/AcceptanceTests/BodyFileLowLevel --e ./Expected/AcceptanceTests/BodyFormDataLowLevel --e ./Expected/AcceptanceTests/BodyFormUrlEncodedDataLowLevel --e ./Expected/AcceptanceTests/BodyIntegerLowLevel --e ./Expected/AcceptanceTests/BodyNumberLowLevel --e ./Expected/AcceptanceTests/BodyStringLowLevel --e ./Expected/AcceptanceTests/BodyTimeLowLevel --e ./Expected/AcceptanceTests/ConstantsLowLevel/ --e ./Expected/AcceptanceTests/CustomBaseUriLowLevel --e ./Expected/AcceptanceTests/CustomBaseUriMoreOptionsLowLevel --e ./Expected/AcceptanceTests/ErrorWithSecretsLowLevel/ --e ./Expected/AcceptanceTests/ExtensibleEnumsLowLevel --e ./Expected/AcceptanceTests/HeaderLowLevel --e ./Expected/AcceptanceTests/HttpLowLevel --e ./Expected/AcceptanceTests/IncorrectErrorResponseLowLevel --e ./Expected/AcceptanceTests/MediaTypesLowLevel --e ./Expected/AcceptanceTests/MergePatchJsonLowLevel --e ./Expected/AcceptanceTests/ModelFlatteningLowLevel --e ./Expected/AcceptanceTests/MultipleInheritanceLowLevel --e ./Expected/AcceptanceTests/NoOperationsLowLevel --e ./Expected/AcceptanceTests/NonStringEnumsLowLevel --e ./Expected/AcceptanceTests/ObjectTypeLowLevel --e ./Expected/AcceptanceTests/ParameterFlatteningLowLevel --e ./Expected/AcceptanceTests/ParameterizedEndpointLowLevel/ --e ./Expected/AcceptanceTests/ReportLowLevel --e ./Expected/AcceptanceTests/RequiredOptionalLowLevel --e ./Expected/AcceptanceTests/ReservedWordsLowLevel --e ./Expected/AcceptanceTests/UrlLowLevel --e ./Expected/AcceptanceTests/UrlMultiCollectionFormatLowLevel --e ./Expected/AcceptanceTests/ValidationLowLevel --e ./Expected/AcceptanceTests/XmlLowLevel --e ./Expected/AcceptanceTests/XmsErrorResponseLowLevel --e ./Expected/AcceptanceTests/SecurityAadSwaggerLowLevel --e ./Expected/AcceptanceTests/SecurityKeySwaggerLowLevel diff --git a/test/vanilla/low-level/tox.ini b/test/vanilla/low-level/tox.ini deleted file mode 100644 index 15506f14779..00000000000 --- a/test/vanilla/low-level/tox.ini +++ /dev/null @@ -1,16 +0,0 @@ -[tox] -envlist=py36, py310 -skipsdist=True - -[testenv] -passenv=* -deps= - -rrequirements.txt -commands= - pytest --cov=Expected - -[testenv:ci] -deps= - -rrequirements.txt -commands = - pytest --cov=Expected AcceptanceTests From 01729d3422464b1dbc905cf1e67204cd9f8f5cb9 Mon Sep 17 00:00:00 2001 From: iscai-msft Date: Thu, 16 Jun 2022 10:35:46 -0700 Subject: [PATCH 4/4] add back versiontolerant to namespace --- tasks.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/tasks.py b/tasks.py index 680a4de478b..91ec0fd7fbb 100644 --- a/tasks.py +++ b/tasks.py @@ -226,6 +226,8 @@ def _build_flags( if generator == _Generator.LEGACY: override_flags["payload-flattening-threshold"] = 1 override_flags["version-tolerant"] = False + else: + namespace += "versiontolerant" flags = { "use": AUTOREST_DIR,